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
asked Jan 24, 2017 at 21:08
chendriksen
1,0246 gold badges17 silver badges31 bronze badges
-
1Also note that what you have in your expected output isn't JSON. JSON requires keys to be quoted.Brad– Brad2017年01月24日 21:10:25 +00:00Commented Jan 24, 2017 at 21:10
-
@Brad fixed. Thank you!chendriksen– chendriksen2017年01月24日 21:12:15 +00:00Commented Jan 24, 2017 at 21:12
-
2Not sure why anyone is downvoting this question. It's a completely valid question, with example code, expected output, and what was tried...Brad– Brad2017年01月24日 21:12:57 +00:00Commented Jan 24, 2017 at 21:12
-
It has a shitty title, though. And it's a trivial typo.dumbass– dumbass2024年07月13日 08:18:43 +00:00Commented Jul 13, 2024 at 8:18
2 Answers 2
var myObject = []; should be var myObject = {};
answered Jan 24, 2017 at 21:09
Salih Şenol Çakarcı
2,33015 silver badges23 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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);
answered Jan 24, 2017 at 21:12
Mike Cluck
32.6k13 gold badges84 silver badges95 bronze badges
Comments
lang-js