Search code examples
javascriptjsonstringify

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!


Solution

  • 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