Cheung
Cheung

Reputation: 15552

JavaScript eval() JSON issue

I have the JSON string below :

{ "name":"Ruby on Rails Baseball Jersey", "price":"19.99",
"id":"1025786064",
"image":"http://127.0.0.1:3001/assets/products/4/product/ror_baseball.jpeg" }, { "name":"Ruby on Rails Baseball Jersey", "price":"19.99",
"id":"1025786064",
"image":"http://127.0.0.1:3001/assets/products/5/product/ror_baseball_back.jpeg" }, { "name":"Ruby on Rails Ringer T-Shirt", "price":"19.99",
"id":"187438981",
"image":"http://127.0.0.1:3001/assets/products/9/product/ror_ringer.jpeg" }, { "name":"Ruby on Rails Ringer T-Shirt", "price":"19.99",
"id":"187438981",
"image":"http://127.0.0.1:3001/assets/products/10/product/ror_ringer_back.jpeg" }, { "name":"Apache Baseball Jersey", "price":"19.99",
"id":"706676762",
"image":"http://127.0.0.1:3001/assets/products/1004/product/apache_baseball.png" }, { "name":"Ruby Baseball Jersey", "price":"19.99", "id":"569012001", "image":"http://127.0.0.1:3001/assets/products/1008/product/ruby_baseball.png" }

Then in jQuery:

var d = eval("(" + data + ")"); //data is the json string above.

$.each(d, function(idx, item) {
 alert(item);      
});

There is no error, but it only shows the first sequence's data. How can I loop through all the data?

Thank you.

Upvotes: 0

Views: 2059

Answers (5)

Piotr Rochala
Piotr Rochala

Reputation: 7781

Firstly, make sure you use JSON parser from here: https://github.com/douglascrockford/JSON-js/blob/master/json2.js

then your code will look somewhat like this:

var myArrayOfObjects = JSON.parse("[" + data + "]");
for (obj in myArrayOfObjects)
{
   alert("Name:" + myArrayOfObjects[obj].name);
}

or in Jquery:

$.each(myArrayOfObjects , function(i, o) {
 alert("Name:" + o.name);      
});

Upvotes: 1

hydrogen
hydrogen

Reputation: 2876

Try wrapping your JSON with [ ]

You can validate your JSON here: JSONLint Validator to get some sense as to where the problem lies.

Upvotes: 1

adamk
adamk

Reputation: 46804

Try:

var d = eval("[" + data + "]");

JSON arrays are wrapped in square brackets, e.g.: '[ 1,2,3 ]'

(Yes, and don't use eval but the JSON built-in object or similar, safer solutions)

Upvotes: 1

Q2Ftb3k
Q2Ftb3k

Reputation: 688

Crockford advises against using eval to parse JSON, so you should be using the JSON.parse function.

Here is where you would use it:

http://www.json.org/js.html

Upvotes: 1

Delan Azabani
Delan Azabani

Reputation: 81384

Using eval() to parse JSON is unsafe. Try using the browser-native (no libraries needed!) function JSON.parse() instead, which is implemented across all browsers and is secure.

Upvotes: 1

Related Questions