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.
-
1Just to be pedantic: those are not "JSON strings", those are JavaScript objects declared with object literal syntax.Pointy– Pointy2013年03月26日 15:17:34 +00:00Commented Mar 26, 2013 at 15:17
-
@Pointy That's not pedantic, that's a very important distinction.James M– James M2013年03月26日 15:27:25 +00:00Commented 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"..... ?Rodniko– Rodniko2013年03月26日 15:42:31 +00:00Commented Mar 26, 2013 at 15:42
-
@Pointy can you please explain? i don't know what you mean...Rodniko– Rodniko2013年03月26日 16:19:15 +00:00Commented 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.Pointy– Pointy2013年03月26日 16:35:12 +00:00Commented Mar 26, 2013 at 16:35
2 Answers 2
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.
2 Comments
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" }]