Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 515
Skittles Avatar asked Jul 31 '26 23:07

Skittles


1 Answers

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
like image 187
Robin Avatar answered Aug 03 '26 14:08

Robin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!