Skittles
Skittles

Reputation: 2918

JSON.stringify seeming to not work as expected

I have the following code;

var rawData = [];
rawData['uid'] = 105;
rawData['auth_customer'] = true;
console.log(rawData);
var postData = JSON.stringify(rawData);
console.log(postData);

The first console.log is outputting;

[uid: 105, auth_customer: true]

But the last console.log is just returning a []. I need the array turned into a json object. Am I missing something?

Thanks!

Upvotes: 3

Views: 1111

Answers (1)

Robin
Robin

Reputation: 5427

You should define rawData as an Object, not an array. So that you can add or remove additional attributes as key:value pair into it. And to back as an Object you should parse using JSON.parse like this.

    var rawData = {};
    rawData['uid'] = 105;
    rawData['auth_customer'] = true;

    console.log(rawData); // Object

    var postData = JSON.stringify(rawData);
    console.log(postData); // String - "{'uid':105,'auth_customer':true}"

    console.log(JSON.parse(postData)); // Object

Upvotes: 2

Related Questions