-1

I have a JSON file abc.json

{"value1":5.0,"value2":2.5,"value3":"2019-10-24T15:26:00.000Z","modifier":[],"value4":{"value41":{"value411":5,"value412":"hey"}}}

I can get value2 using this regex

sed -E 's/."value2":"?([^,"])"?.*/\1/' abc.json

I want to know how I can get values of value411 and value412

I don't want to use jq or any other tool as my requirement is to use regex for this.

tripleee
  • 175,061
  • 34
  • 275
  • 318
user18148705
  • 215
  • 1
  • 11
  • 2
    Don't use regex for getting content out of JSON. Use a parser. If you give me a regex that seems to work, I will give you JSON for which it doesn't. – trincot Oct 27 '22 at 09:26

2 Answers2

0

You should always try to use an existing parser, depending on what platform you work on there should be one that can interpret the data model for you.

I refer to this famous answer about parsing HTML with regex

Thom Ernst
  • 379
  • 1
  • 4
  • 15
  • Thanks, i have updated my question. I want to use regex only as my requirement is to perform this basic operation using regex – user18148705 Oct 27 '22 at 08:51
0
   var jData = {
        "value1": 5.0,
        "value2": 2.5,
        "value3": "2019-10-24T15:26:00.000Z",
        "modifier": [],
        "value4": {
            "value41": {
                "value411": 5,
                "value412": "hey"
            }
        }
    };

If You try with regex then use this:

JSON.stringify(jData).match(/(?<=(\"(value411|value412)\"\:))[\"\w+]+/g)
// Output: ['5', '"hey"']

Demo: https://regex101.com/r/c3K4cH/1

Limitation: You have to put only the key name, don't try to fetch the full object

You create a javascript function get any non-empty value from a JSON, as follows:

function getData(obj, fKey, fData = null) {
    for (const prop of Object.getOwnPropertyNames(obj)) {
        if (!fData) {
            if (typeof obj[prop] === 'object' && Object.keys(obj[prop]).length > 0 && prop !== fKey) {
                return getData(obj[prop], fKey, fData)
            } else {
                if(prop === fKey) {
                    fData =  obj[prop];
                    return fData
                }
            }
        } else {
            return fData;
        }
    }
}

console.log(getData(jData, 'value411'));
console.log(getData(jData, 'value412'));
Art Bindu
  • 769
  • 4
  • 14
  • Hey thanks for the response. I am trying to run commands in windows subsystem for linux. So the command I tried was sed -E '(?<=(\"(value411|value412)\"\:))[\"\w+]+' abc.json but this gave me sed: -e expression #1, char 1: unknown command: `(' – user18148705 Oct 27 '22 at 09:53
  • hey Bindu sir could you please tell me the exact regex in this that I can use via linux command line to get the particular data – user18148705 Oct 27 '22 at 12:03