midryuk
midryuk

Reputation: 85

Why I can't parse JSON in JavaScript?

JSON contains one object:

results[0] = { 'MAX(id)': 1 }

And this code doesn't work:

var text = results[0];
var obj = JSON.parse(text);
console.log(obj.MAX(id));

Upvotes: 2

Views: 3734

Answers (4)

ozil
ozil

Reputation: 7117

    var results = { 'MAX(id)': 1 };
    //var text = results;
    //var obj = JSON.parse(text);
    alert(results['MAX(id)']);

Upvotes: 1

Shilly
Shilly

Reputation: 8589

Your result[0] is a real javascript object. JSON.parse transforms text into objects, so you can't parse other objects with it.

Upvotes: 1

TaoPR
TaoPR

Reputation: 6052

Your object is already a JSON. You don't need to parse it. To access MAX(id) property, you can use [] notation as follows:

results[0] = { 'MAX(id)': 1 };
console.log(results[0]['MAX(id)']);

Upvotes: 1

suvroc
suvroc

Reputation: 3062

results[0] is already an object type

You can parse only from string to object like this:

JSON.parse('{ "MAX(id)": 1 }');

Upvotes: 1

Related Questions