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());
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():Alternatively, there is a native JavaScript function
JSON.parse()in most browsers to do this: