Getting value from a JSON string with space in key

Viewed 181

I have a json string as below. I want to get value within it by referring to a particular key. I tried accessing it directly and also tried using a loop. Both failed:

{"CGST - FU": 9.0, "SGST - FU": 9.0}

What am I doing wrong?

var data = '{"CGST - FU": 9.0, "SGST - FU": 9.0}'

//Get value of key 
console.log(data['CGST - FU']);
    
 for (var key of Object.keys(data)) {
      console.log(key + " -> " + data[key])
 }
    

3 Answers

You need use JSON.parse for change string of object to object

var data = '{"CGST - FU": 9.0, "SGST - FU": 9.0}'

console.log(JSON.parse(data)['CGST - FU']);

This works,

var data = '{"CGST - FU": 9.0, "SGST - FU": 9.0}'

const value = data.match("CGST - FU")
value[0] // CGST - FU

Your data is in string format. So your keys are index & value is character at that index. You'll need to parse it to JSON first. Check below implementation:

var dataString = '{"CGST - FU": 9.0, "SGST - FU": 9.0}'
var data = JSON.parse(dataString)//json format
//Get value of key 
console.log(data['CGST - FU']);
    
 for (var key of Object.keys(data)) {
      console.log(key + " -> " + data[key])
 }

Related