0

The JS array containing JSON objects is in external file pairs.js which looks like this:

var objects =[{
    "name":"Joe",
    "age":"22"
  },{
    "name":"April",
    "age":"43"
  }, .......
];

I include the file in html like this:

<script src="pairs.js"></script>

Now my problem begins - I can't parse these objects. I've done it like this:

var obj=jQuery.parseJSON(objects);
//also tried: jQuery.parseJSON(objects[0]);
alert(obj.name);

But it won't work. What am I doing wrong?

4
  • 8
    You've used JavaScript literal syntax to create JavaScript objects. That isn't JSON. There's nothing to parse since it's already in the native object types of the programming environment. Commented Oct 10, 2012 at 15:54
  • 2
    I read the expression JSON object in this site about 20 times a day... Commented Oct 10, 2012 at 15:57
  • 2
    There is no such thing as a "JSON Object". JSON is a string representation of an object (it just happens to be similar to the JavaScript object syntax). Commented Oct 10, 2012 at 15:58
  • Thanks for clarifying. I've been trying to resolve this before asking here but obviously I'm still a greenhorn in web dev :) Thanks again Commented Oct 10, 2012 at 16:00

3 Answers 3

4

jQuery.parseJSON() expects a string argument that contains JSON. But you're passing it an already-formed object. You don't need to parse anything at all here. Just use objects.

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

1 Comment

Thank you, alert(objects[0].name] did it!
0

objects is already a JavaScript object and parseJson() won't work in this case

Comments

0

You are already passing a formed Object, so there is no need to parse it, just try using the object.

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.