0

I'm using Firefox 19.0.2. I receive a JSON string (into a JavaScript function) with changing sizes,

sometimes it is:

var jsonstring = {"CA":"CA","NY":"NY","TX":"TX"}

sometimes it is:

var jsonstring = {"Hello":"Hello","Goodbye":"Goodbye"}

I want to create a result array like this (in case of the first example):

data[0].value = "CA"
data[0].text = "CA"

data[1].value = "NY"
data[1].text = "NY"

data[2].value = "TX"
data[2].text = "TX"

How do I do that?

I read tens of early posts here and tried a couple of for loops, but nothing works.

5
  • 1
    Just to be pedantic: those are not "JSON strings", those are JavaScript objects declared with object literal syntax. Commented Mar 26, 2013 at 15:17
  • @Pointy That's not pedantic, that's a very important distinction. Commented Mar 26, 2013 at 15:27
  • Could this be the reason that when i loop on jsonstring with indexes: jsonstring[0], jsonstring[1]... i get letters instead of strings? jsonstring[0] = "{" ,jsonstring[1] = """,jsonstring[2] = "C"..... ? Commented Mar 26, 2013 at 15:42
  • @Pointy can you please explain? i don't know what you mean... Commented Mar 26, 2013 at 16:19
  • 1
    @Rodniko well a JSON string is a string value that contains (unparsed) JSON. What you posted are JavaScript object literal expressions. They look like JSON because JSON is a simplified form of JavaScript object literal syntax, but they don't need parsing because the JavaScript interpreter already parsed them. Commented Mar 26, 2013 at 16:35

2 Answers 2

1

You can use JSON.parse to convert to an object (In your example you arleady have an object though):

var obj= JSON.parse('{"CA":"CA","NY":"NY","TX":"TX"}')

Keep in mind, you can't depend on the order of the attributes in an object, so you could not accomplish what you are trying to do above in a for loop.

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

2 Comments

Thank you Justin, but what do i do afterwards? i tried a loop but there is no obj[0]. i also tried obj[0].key but it doesn't work. how do i read the content of obj in a loop after the parsing?
Try pasting the above code into your browsers console, chrome has a good one. Then play around with the object, example: obj.CA == 'CA'
0

The transform after using JSON.parse to get an object from the JSON, would look something like that:

obj = {
  CA: 'CA',
  LA: 'LA'
};

arr = [];

for (var key in obj) {
  if(!obj.hasOwnProperty(key))
    continue;
  arr.push({value: key, text: obj[key]});
}
// Output
[{ value: "CA", text: "CA" }, { value: "LA", text: "LA" }]

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.