0

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

4
  • 1
    Also note that what you have in your expected output isn't JSON. JSON requires keys to be quoted. Commented Jan 24, 2017 at 21:10
  • @Brad fixed. Thank you! Commented Jan 24, 2017 at 21:12
  • 2
    Not sure why anyone is downvoting this question. It's a completely valid question, with example code, expected output, and what was tried... Commented Jan 24, 2017 at 21:12
  • It has a shitty title, though. And it's a trivial typo. Commented Jul 13, 2024 at 8:18

2 Answers 2

8

var myObject = []; should be var myObject = {};

Sign up to request clarification or add additional context in comments.

Comments

3

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.