1

I have a JSON string like this

{"3560" : "something", "3980" : "something", "4580" : "1456"}

How to get data above as "key -> value" in javascript(jquery) ?

2 Answers 2

5
var obj = JSON.parse(jsonString);

Now you can access obj["3560"], etc.

Or iterating:

for(var key in obj) {
    // do something with obj[key]
}
Sign up to request clarification or add additional context in comments.

2 Comments

is JSON.parse now included in every browser?
@Anders: Actually I'm not 100% sure in which browsers it is supported, but it can always be included: github.com/douglascrockford/JSON-js I would not include jQuery for only parsing JSON. But if it is used anyway, then $.parseJSON() should be preferred.
1
var obj = jQuery.parseJSON(jsonObj);

Then you could access the data like obj.3560 or obj.3980 or iterate over them using a for-in loop like in Felix Kling's answer.

This requires jquery 1.4.1 or later to work.

6 Comments

If I use obj.3560, obj.3980 etc. I will get only the "value" of 3560, 3980. I`m trying to get and the key (3560, 3980) also
@John - They will be contained in the obj var. This was just an example on how to access the value after you parse it. Do a for-in loop and you will be able to access the keys as well.
obj.3560 should not work as a number is not a valid identifier.... does this really work for you?
@John: Is the for loop in my answer not example enough?
@ Felix Kling: With the example you showed I got only values, but not the keys
|

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.