zuestech
zuestech

Reputation: 93

Getting value from a JSON string with space in key

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])
 }
    

Upvotes: 2

Views: 837

Answers (3)

Anshul
Anshul

Reputation: 94

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])
 }

Upvotes: 2

Mohamed Ali
Mohamed Ali

Reputation: 141

This works,

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

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

Upvotes: 2

AlexAV-dev
AlexAV-dev

Reputation: 1175

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']);

Upvotes: 2

Related Questions