Simon Davies
Simon Davies

Reputation: 3686

JSON add two fields together

I have a static json file (below) and I then also create a new json file via php form data retrieved.

Both files have the same data structure and I would like to combine them both together if that is possible?

        {
          "year": [{
              "yr": "2012",
              "items": [{
                      "id": 2,
                      "title": "lorem epsum",
                      "desc": "lorem epsum",
                      "img": "myimage.jpg"
                  }],
              "aid": 2
              }]
        };

both files have the following data that I would like to merge:

      "yr": "2012",
      "items": [{
              "id": 2,
              "title": "lorem epsum",
              "desc": "lorem epsum",
              "img": "myimage.jpg"
          }],
      "aid": 2

So how could I add/merge these two files together? PHP or JS or both? Thanks

Upvotes: 1

Views: 1280

Answers (2)

Joko Wandiro
Joko Wandiro

Reputation: 1987

Javascript Object Notation (JSON) combine Javascript Objects and Javascript Arrays.

Javascript Arrays using ([]), Javascript Objects ({}).

If you want to add your data,

you can use Array's push method on part which Arrays contains your object.


$(document).ready( function(){  
        data= {
          "year": [{
              "yr": "2012",
              "items": [{
                      "id": 2,
                      "title": "lorem epsum",
                      "desc": "lorem epsum",
                      "img": "myimage.jpg"
                  }],
              "aid": 2
              }]
        };

        data2= {
            "yr": "2013",
            "items": [{
                "id": 2,
                "title": "lorem epsum",
                "desc": "lorem epsum",
                "img": "myimage2.jpg"
            }],
            "aid": 2
            }
        data.year.push(data2);

        $.each(data.year, function(){
            console.log(this.yr);
        });
});

Upvotes: 1

bescht
bescht

Reputation: 26

If you're using jQuery you could try this with

jQuery.extend(target, object)

(of course after you parsed the JSON file to a Javascript object with JSON.parse()...)

See jQuery documentation: http://api.jquery.com/jQuery.extend/

Upvotes: 0

Related Questions