1

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());
Cœur
39k25 gold badges207 silver badges282 bronze badges
asked Jan 20, 2013 at 10:10
6
  • try this var content = Eval($("textarea").val()); you must convert it a json object Commented Jan 20, 2013 at 10:12
  • I had to make Eval less eval by removing the capital E ;-) Now I get a little bit further and am running into the error SyntaxError: invalid label Commented Jan 20, 2013 at 10:17
  • What do you get when you do a console.log(content);? Commented Jan 20, 2013 at 10:18
  • 1
    @DON: Never use eval for parsing JSON!!! Commented Jan 20, 2013 at 10:21
  • learned en forgot again, despite that, @DON : thanks for taking the effort! Commented Jan 20, 2013 at 10:26

2 Answers 2

5

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() );
answered Jan 20, 2013 at 10:16
Sign up to request clarification or add additional context in comments.

Comments

3

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']
answered Jan 20, 2013 at 10:18

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.