Home > Enterprise >  REGEX FOR FETCHING JSON DATA
REGEX FOR FETCHING JSON DATA

Time:10-27

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.

CodePudding user response:

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

CodePudding user response:

   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'));
  • Related