I have this JSON string:
{"image":[
{"img":"_files\/image\/images\/firstimage.jpg","alt":"firstimage alt text"},
{"img":"secondimage.jpg","alt":"secondimage alt text"}
]}
The JSON string is picked from a textarea, then stored in the variable 'content'
var content = $("textarea").val();
I am trying to access the elements:
alert(content["image"][0]["img"]);
But I get error:
TypeError: content.image is undefined.
Eventually I want to manipulate the JSON string by changing and adding elements.
What am I doing wrong here?
UPDATE
$.parseJSON did the job:
var content = $.parseJSON($("textarea").val());
2 Answers 2
If you're picking the JSON string from a textarea, you must first convert it to a JavaScript object, before using it. Use, e.g., $.parseJSON():
var content = $.parseJSON( $("textarea").val() );
Alternatively, there is a native JavaScript function JSON.parse() in most browsers to do this:
var content = JSON.parse( $("textarea").val() );
Comments
It won't parse straight to JSON instead you'll need to first do
var content = JSON.parse($("textarea").val());
This should then allow you to use general JSON manipulation
Example of your JSON retrieval could be something like this
content.image[0]['alt']
var content = Eval($("textarea").val());you must convert it ajsonobjectevalfor parsing JSON!!!