1

I've just started to learn how to use JSON and this is probably a noob question: ¿why do I have to parse JSON?

I've a JSON object that comes from a php array (I've used it json_encode) and it looks like this:

var jason = 
{
  "book1": {
    "price": 10,
    "weight": 30
  },
  "book2": {
    "price": 40,
    "weight": 60
  }
};

and I can loop through it using the $.each() function, so why would I parse it? After apllying a parse, I cant use $.each() anymore, dunno why. And I dont understand why I cant use something like this: console(jason.book1[1]);

I know that the description in jquery says:

Description: Takes a well-formed JSON string and returns the resulting JavaScript object.

But I dont really get it. Anyway, any help would be appriciated!

3
  • What you have is a javascript object, not JSON. It just so happens that javascript objects share similar syntax with JSON strings. Commented Oct 31, 2012 at 1:06
  • As others said, that's a JavaScript object, not JSON. Think about JSON as being like XML which is typically also parsed before you do anything with it. If you use PHP and inject an JSON encoded array into JS, then you just take advantage of the fact that JSON is valid JS if interpreted as such. That's more or less coincidence. Commented Oct 31, 2012 at 1:09
  • There's no such thing as a JSON object. Commented Oct 31, 2012 at 1:41

2 Answers 2

2

The above is an object in JavaScript (not technically JSON, since JSON is just a notation for representing objects rather than a data structure. It's pedantic to say that, though):

However, say you had a string like this:

var jason = '{"book1":{"price":10,"weight":30},"book2":{"price":40,"weight":60}}';

You could get that string in a variety of ways, but say you have it.

$.parseJSON(jason) will turn that string into the object you have above.

See? http://jsfiddle.net/7Qvd2/

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

2 Comments

Thanks for your answer. But, even after parsing it, I still can't use jsonparsed.book1[0]
@mat book1 doesn't have a 0 property. Try book1.price
1

JSON is a representation of data. When it comes from HTML or over XHR, it's always a string (just a sequence of characters). It has no meaning except for the individual characters that compose it. The : that points a property to its value has no different meaning than a : which may appear in a string in your JSON.

You must parse it to get a usable version of it, that is, the string transformed into a native data structure in your language. This parses the string into its components. In JavaScript, that's it transformed into objects, arrays, booleans, nulls, numbers, etc. In other languages, there are equivalent types and structures.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.