Reputation: 1024
I've got a JavaScript object where I've pushed values...
var myObject = [];
myObject.name = "Steve"
myObject.job = "Driver"
Now I want to get those values as JSON, i.e.
{ "name": "Steve", "job": "Driver" }
is this possible? I've tried JSON stringify but it returns an empty object
Upvotes: 0
Views: 74
Reputation: 32511
For starters, make sure you're creating an object not an array. An array is an ordered list of data where as an object is an unordered group of key-value pairs. As such, they're serialized differently.
var myObject = {}; // <-- Changed [] to {}
myObject.name = "Steve";
myObject.job = "Driver";
// Alternatively, you can do this
var myObject = {
name: 'Steve',
job: 'Driver'
};
Converting it to JSON is as easy as calling JSON.stringify
.
var myObject = {
name: 'Steve',
job: 'Driver'
};
var json = JSON.stringify(myObject);
console.log(json);
Upvotes: 3