epsilones
epsilones

Reputation: 11627

Parsing json data failing - jquery

I don't know where I ma missing something but I have this

var myvar = [{"id":1,"name":"name1"},{"id":2,"name":"name2"}];

and I tried this

$(jQuery.parseJSON(JSON.stringify(myvar))).each(function() {  
        console.log(this.name);
});

But I have an error in my console : Syntax error, unrecognized expression [{"id":1,"name":"name1"},{"id":2,"name":"name2"]

I am missing something, but I don't know what ?

Edit : in fact when I copy paste the myvar in my console and run the parsing then it works ?? But, when I refresh my page and when I retrieve myvar as so : console.log(myvar), I get [{"id":1,"name":"name1"},{"id":2,"name":"name2"}], without normally told by chrome's console that it is an object

Upvotes: 0

Views: 272

Answers (4)

epsilones
epsilones

Reputation: 11627

This is the correct syntax :

$(jQuery.parseJSON(myvar)).each(function() {  
    console.log(this.name);
});

(In fact, when I copy paste the myvar in my console and run the parsing then it works. But, when I refresh my page and when I retrieve myvar as so : console.log(myvar), I get [{"id":1,"name":"name1"},{"id":2,"name":"name2"}], without normally told by chrome's console that it is an object )

Upvotes: 0

Robin van Baalen
Robin van Baalen

Reputation: 3651

That's weird; I get an error as well trying your code. It seems perfectly fine though.

Why don't you just try this:

jQuery(myvar).each(function () {
    console.log(this.name);
});

this outputs

name1
name2

in my console. This seems to be a solution for you since you're already converting the object to a string and back to an object (array).

Upvotes: 0

Anton
Anton

Reputation: 32591

you are missing a } at the end

var myvar = [{"id":1,"name":"name1"},{"id":2,"name":"name2"}];

Upvotes: 2

Aram Kocharyan
Aram Kocharyan

Reputation: 20431

You're not closing the object.

var myvar = [{"id":1,"name":"name1"},{"id":2,"name":"name2"}];

Upvotes: 3

Related Questions