-1

I need to import a few external json data into a variable or into a single json file to then display that data with D3.

This is the format of the data that I need to import from each json file:

    {
      "name": "name1",
      "version": "0.1.2",

      "references": [
        {
          "url1": "http://example1.com"
        },
        {
          "url2": "http://example2.com"
        }
      ]
    }

And this is the format of data that I need for the final json file/variable.

    {
      "nodes":[
        {
          "name": "name1",
          "version": "0.1.2",
          "references": [
            {
              "url1": "http://example1.com"
            },
            {
              "url2": "http://example2.com""
            }
          ]
        },

        {
          "name": "name2",
          "version": "1.6.0",
          "references": [
            {
              "url1": "http://example34.com"
            },
            {
              "url2": "http://example30.com""
            }
          ]
        },
        {
          ...
          ...
        }
      ],
      "links":[
      ]
    }

Basically I need to merge the data from the different json files inside the "nodes" array.

Any idea how could I do this? Thanks

Liam
  • 27,717
  • 28
  • 128
  • 190
faia20
  • 2,204
  • 2
  • 11
  • 8

2 Answers2

2

nodes is a simple array, so you can just push the 'file' objects into the nodes array.

var file1 = {
    "name": "name1",
    "version": "0.1.2",
    "references": [
        {
            "url1": "http://example1.com"
        },
        {
            "url2": "http://example2.com"
        }
    ]
}

var file2 = {
    "name": "name1",
    "version": "0.1.2",
    "references": [
        {
            "url1": "http://example1.com"
        },
        {
            "url2": "http://example2.com"
        }
    ]
}

var files = [file1, file2];

var node = {
    "nodes": [],
    "links": []
}

files.forEach(function(file) {
    node.nodes.push(file);
})

console.log(node);
Marc Dix
  • 1,864
  • 15
  • 29
0

If you simply need to push all the data from the imported JSON into nodes, you can do this:

var imported =  {
    "name": "name1",
    "version": "0.1.2",
    "references": [
        {
            "url1": "http://example1.com"
        },
        {
            "url2": "http://example2.com"
        }
    ]
};

var finalJson = {
    nodes: []
};

finalJson.nodes.push(imported);

Here is the fiddle: https://jsfiddle.net/vj1nqeu5/1/

Gerardo Furtado
  • 100,839
  • 9
  • 121
  • 171