2

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 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

2

This works,

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.