2

I have here JSON data. I would like to add new property which is an array. Please see below what it looks like:

var datList = [];
var data = {
  id: '1',
  name: 'mike'
};
data = JSON.parse(JSON.stringify(data));
var arr = [{prop1: '1', prop2: '2'}, {prop1: 'one', prop2: 'two'}];

data.new_arr = arr;

datList.push(data);
console.log(datList);

That gives me this:

{
     id:'1',
     name: 'mike'
     new_arr: [[Object], [Object]]
}

Desired JSON data

 [{
     id:'1',
     name: 'mike',
     new_arr: [{prop1: '1', prop2: '2'}, {prop1: 'one', prop2: 'two'}]
 }]
1
  • Also, none of your examples is JSON. JSON is a textual notation for data exchange. If you're dealing with source code, and not dealing with a string, you aren't dealing with JSON. Commented Jan 4, 2016 at 15:51

2 Answers 2

2

Your code produces exactly the structure you've said you wanted, the main issue here is that you're having trouble interpreting the console output, which is fair enough — web consoles can take some getting used to, and sometimes show things in a less-than-useful way. (Secondarily, JSON is irrelevant in your code. You're just dealing with JavaScript objects [except very temporarily on one line that serves no purpose]. And you've quoted output that must be from an earlier version of your code.)

Console output

You've said:

That gives me this:

{
     id:'1',
     name: 'mike'
     new_arr: [[Object], [Object]]
}

That's just how whatever console you're using is showing it to you; presumably, each of those [Object] is something you could expand with the mouse. Separately, I think that that quote is from an earlier version of your code, as it is missing the outer array, but your code clearly shows you logging datList, not data.

Different web consoles behave differently, and some of them even behave differently depending on whether you log something with the console closed and then open it or log it with the console open. To make things even more confusing, when you log an object, with most consoles the console has a reference to the object and only shows its top-level structure with an > or similar next to it to expand it, and when you expand it, it shows you that new information as it is then (when you expand it), not as it was originally.

But your code produces the structure you've said you wanted. Let's look at it:

Running your snippet with the console open in Chrome, here's what I get initially (nothing is expanded):

enter image description here

If I then click the > next to the indicated [Object], I get this:

enter image description here

That's called "expanding" that part of the object tree.

If I then expand the indicated [Object], I get this:

enter image description here

And then expanding the indicated new_arr:

enter image description here

And then each of those objects:

enter image description here

If we modify your code snippet slightly so it outputs the JSON that would be produced by JSON.stringify(datList):

var datList = [];
var data = {
  id: '1',
  name: 'mike'
};
data = JSON.parse(JSON.stringify(data));
var arr = [{prop1: '1', prop2: '2'}, {prop1: 'one', prop2: 'two'}];

data.new_arr = arr;

datList.push(data);
console.log(   JSON.stringify(datList, null, 2));
// Only change ^^^^^^^^^^^^^^^       ^^^^^^^^^^

We get:

[
  {
    "id": "1",
    "name": "mike",
    "new_arr": [
      {
        "prop1": "1",
        "prop2": "2"
      },
      {
        "prop1": "one",
        "prop2": "two"
      }
    ]
  }
]

...which is exactly the structure you said you wanted.

JSON

There's no JSON anywhere in your code except temporarily during this line:

data = JSON.parse(JSON.stringify(data));

That takes an existing JavaScript object, creates JSON for it, then parses that JSON, and assigns the new, equivalent JavaScript object to data. It serves no purpose at all in that code.

In my snippet above, I used JSON at the end purely to show the structure of datList in a fairly clear and concise way.

Here's a slightly modified version of your code with no JSON at all, which demonstrates that you've succceeded in creating the structure you said you wanted:

var datList = [];
var data = {
  id: '1',
  name: 'mike'
};
var arr = [{prop1: '1', prop2: '2'}, {prop1: 'one', prop2: 'two'}];

data.new_arr = arr;

datList.push(data);

snippet.log(datList.length);               // 1
snippet.log(datList[0].id);                // 1
snippet.log(datList[0].name);              // mike
snippet.log(datList[0].new_arr[1].prop1);  // one
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

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

4 Comments

I'm using nodejs to produced this.
@Michael: Right, that's how Node's console works (as I said, they vary). And if you do as I suggest above (console.log(JSON.stringify(datList));), you'll see that your structure is correct: i.sstatic.net/8A2Er.png
what are the other 2 parameter on stringify(datList,null,2) for?
@Michael: JSON.stringify: spec | MDN. The second is for a "replacer function" (null = none), the second is the indentation for pretty-printing.
1

I just ran your code in the console while trying to find the solution to your issue and created this snippet.

// the data you have
var data = {
  id: '1',
  name: 'mike'
}
// the data you'd like to add to your JSON
var arr_to_add = [{ prop1: '1', prop2: '2' }, { prop1: 'one', prop2: 'two' }]

// parse the raw data (without the array added)
var data_as_json = JSON.stringify(data);

// write a line to show how the original JSON looks
document.write(data_as_json + "<br />");

// convert the parsed JSON back to a JS object
var data_parsed = JSON.parse(data_as_json);

// add the array (can also be done via dot notation: data_parsed.new_arr = arr_to_add)
data_parsed['new_arr'] = arr_to_add;

// convert the parsed_data with the array back to JSON
var final_data = JSON.stringify(data_parsed);

// convert the parsed_data with the array added and itself wrapped in an array
var final_data_2 = JSON.stringify([data_parsed]);

// show the new json
document.write(final_data + "<br />");

// show the new wrapped JSON
document.write(final_data_2);

I think that you forgot to use JSON.stringify on the end result (in my case final_data) - I'm not sure because I'm not seeing the entire code here.

JSON.stringify is needed to turn JS data structures (however deeply nested they may be) back into JSON.

EDIT 05-01-2016

Based on your comment (@OP) All you need to do is wrap the entire object you want in an array literal ([])

I edited the above snippet to reflect this behaviour, basically in my example - data_parsed is your object and final_data simply calls JSON.stringify on it.

All you seem to want to do is wrap this object in an array which is fairly simple to achieve by changing the input to JSON.stringify.

The following two lines in my example display the difference.

var final_data = JSON.stringify(data_parsed);
var final_data_2 = JSON.stringify([data_parsed]);

Now there are two things different here, the first is the variable name but this is just for snippet-purposes.

The second thing which is different is the argument passed to JSON.stringify.

JSON.stringify(data_parsed);

changes to

JSON.stringify([data_parsed]);

Remember that when working with JS and JSON and you're converting JS objects or arrays to JSON all you're doing is taking in JS and outputting it to a string with a certain format. This format reflects your structure obviously so if you change your structure you change the JSON - that's all there is to it.

If you plan on appending more objects to this JSON array do that before the JSON.stringify call since that is what's converting the JS to a JSON string.

2 Comments

downvote without comment? - quite surprised about that one, could anyone tell me if I am misunderstanding the question or not solving the issue here?
Not me, I already upvoted your suggestion this works well. However I have edited the given issue. Thanks

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.