Abhinav Abhinav - 3 months ago 8
JSON Question

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 retirieved 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 ?

JAG JAG
Answer

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>