简体   繁体   中英

Nodejs - retrieve value from nested and non-nested json

I am passing json and a key to below function to retrieve its value . The key can be like abc.cde.def nad it can also be like fgh only.

If the keys contain . then it is a nested json and values has to be retrieved accordingly which is happening correctly but if it is a plain json having no nest then it is not working. Printing the length of keysData (in case the key is like fgh) it prints 3 where it should print 1.

function getValueFromJson(jsonInput,keyInput) {
    if(keyInput.includes('.')){
        var keysData = keyInput.split('.');
    }
    else {
        keysData = keyInput.toString()
    }
    var jsonHierarchy = jsonInput;
    if(parseInt(keysData.length) === parseInt('1')){        
        console.log(jsonHierarchy)
        console.log(keysData )
        console.log(jsonHierarchy[keysData ])
        jsonHierarchy = jsonHierarchy[keysData ];
    }   
    return jsonHierarchy;
};

Can anyone please help how can I handle this ?

you dont need to check for if(keyInput.includes('.'))

just do keyInput.split('.')

//for Ex.
'abc.defg'.split('.') // result ['abc', 'defg']
'abc'.split('.')  // result ['abc']

and also

if(parseInt(keysData.length) === parseInt('1'))

//can be used as
if(keysData.length === 1)

and your complete function should be

function getValueFromJson(jsonInput,keyInput) {
    var keysData = keyInput.split('.');

    var jsonHierarchy = jsonInput;
    keysData.forEach(function(d) {
        if(jsonHierarchy)
            jsonHierarchy = jsonHierarchy[d];
    }) 
    return jsonHierarchy;
};

 var jsonData = { 'abc': { 'def': { 'gh': 'value1' }, 'xyz': 'value2' } }; function getValueFromJson(jsonInput, keyInput) { var keysData = keyInput.split('.'); var jsonHierarchy = jsonInput; keysData.forEach(function(d) { if (jsonHierarchy) jsonHierarchy = jsonHierarchy[d]; }) return jsonHierarchy; }; function get() { var val = document.getElementById('key').value; if (val) console.log(getValueFromJson(jsonData, val)); };
 <input id="key" /> <button onclick="get()">Get Value</button>

将您的字符串转换为数组,然后正确显示您的长度。

    var keysData = keyInput.split('.')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM