Alon
Alon

Reputation: 879

Why is JSON parsing necessary?

If I have a JSON array that I’m reciving from the server and I want to use it (for example) for autocomplete — I can just make a JavaScript array, and use a loop to place the JSON values into the array and then use it for my autocomplete.

Is that way really wrong?

Thanks !

Upvotes: 1

Views: 2348

Answers (5)

Muhammad Ali
Muhammad Ali

Reputation: 1330

What Parsing Means?

Parsing generally means interpreting(explain).

What is JSON?

JSON ( JavaScript Object Annotation ) is a format to store data systematically like XML, CSV etc.

What JSON Parsing Means?

Converting data in a format which is more readable to us.

Why it is needed?

  • It is difficult to read Raw JSON Data, Thus we need a format to read it easily. This is where parsing comes in.

  • It is very useful, thus available for almost all lanuanges (like for java here is link )

  • Before parsing, it is just a regular string - u cannot really access the data encoded inside. After parsing, it becomes a Javascript object where u can access the various data within.

Example:

img

Hope it helps.

Upvotes: 0

Billy Moon
Billy Moon

Reputation: 58601

A JSON parser can also ensure the data is valid JSON, which in turn ensures that malicious code can not be injected into your data, and executed on the client.

Upvotes: 1

Alnitak
Alnitak

Reputation: 339927

Originally part of the rationale for JSON was that you could do:

var object = eval(string);

and have the JS interpreter do the parsing directly (see http://www.json.org/js.html)

However the downside with that is that an evil server could include real JS code within that string which your browser would then interpret.

Hence you should always use JSON.parse which will filter out malicious code, or if that's not available include a well maintained compatibility function to do the same job.

Upvotes: 2

SamGoody
SamGoody

Reputation: 14488

The response you receive from the server will be a string, which is not very useful for making a loop.

I assume that you wish to use a split or regex to parse the JSON yourself. That is fine, and is actually safer than eval'ing the incoming data - and quicker than most standard regexs for the task.

However, it loses the advantages of having the incoming data in a format understood by JS, and you are likely to miss something that might theoretically be exploited.

In Firefox 3.1, JSON parsing is native and safe. Once that becomes standard, there would be no benefit to using your own parser. Till then, its a question of tradeoff - how much work would you need to invest for what risk and benefit.

Upvotes: 2

Andy
Andy

Reputation: 30135

You could do it yourself but why? a json parser does just that.

Upvotes: -1

Related Questions