Samuel Segal
Samuel Segal

Reputation: 423

Modifying a JSON Object

I have a JSON generated by Papa Parse from a CSV file that look like this:

{ object, object, object, .... , object }

I need to modify it so it looks like this:

{ "publication" : 
    {
      "id" : 1,
      "name" : "name1"
    },
  "publication" :
    {
      "id" : 2,
      "name" : "name2"
    },
  "publication" :
    {
      "id" : 3,
      "name" : "name3"
    }
}

Where the "id" and "name" are properties within each object.

In other words, I need a JSON that say "publication" and each "publication" occurrence have nested under it the properties names and values of one of the objects above.

How could I achieve this with Javascript?

Thanks

Upvotes: 1

Views: 112

Answers (3)

caiolopes
caiolopes

Reputation: 571

If I understand it right, you probably mean that you have objects like this:

{"publication" : { "id" : 1, "name" : "name1" }
{"publication" : { "id" : 2, "name" : "name2" }
{"publication" : { "id" : 3, "name" : "name3" }

What you can do in order to have:

{ "publication" : [ 
    {
        "id" : 1, 
        "name" : "name1"
    }, 
    {
        "id" : 1, 
        "name" : "name2"
    }, 
    {
        "id" : 3, 
        "name" : "name3"
    } ] 
}

is:

var json = [{"publication" : { "id" : 1, "name" : "name1" }},
                {"publication" : { "id" : 2, "name" : "name2" }},
                {"publication" : { "id" : 3, "name" : "name3" }}];

var newJson = {"publication" : []};

    var i = 0;
    for (var item in json) {
        var key = json[item];
        var obj = {"id" : key["publication"]["id"], "name" : key["publication"]["name"]};
        newJson["publication"][i] = obj;
        i++;
    }

You can check this if you want to print "pretty":

How can I pretty-print JSON using JavaScript?

Upvotes: 1

ste-fu
ste-fu

Reputation: 7482

Is this not an array of publications?

   { publications: [{"id":1, "name":"name1"},
         {"id":2, "name":"name2"}.....]}

Upvotes: 1

Luan Castro
Luan Castro

Reputation: 1184

you cannot put many keys with same name...

a solution it's put in array

{ 
    "publication" : [
      {
        "id" : 1,
        "name" : "name1"
      },
      {
        "id" : 2,
        "name" : "name2"
      },
      {
        "id" : 3,
        "name" : "name3"
      }]
}

Upvotes: 2

Related Questions