21

I have a JSON file with content

{"name" : "Conrad", "info" : "tst", "children" : [
    {"name" : "Rick" },
    {"name" : "Lynn" },
    {"name" : "John", "children": [
        {"name" : "Dave", "children": [
            {"name" : "Dave" },
            {"name" : "Chris" }      
        ]},
        {"name" : "Chris" }
    ]}
  ]};

I want to import this JSON file data inside a JavaScript file and have the final result like

var treeData ={"name" : "Conrad", "info" : "tst", "children" : [
        {"name" : "Rick" },
        {"name" : "Lynn" },
        {"name" : "John", "children": [
                {"name" : "Dave", "children": [
                {"name" : "Dave" },
                {"name" : "Chris" }

         ] },
                {"name" : "Chris" }
         ]}
  ]};

I've tried many code samples but none have worked.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
user3248233
  • 221
  • 1
  • 2
  • 5

4 Answers4

12

Parse the content of the file like this:

var treeData = JSON.parse(fileContent);

You don't describe how you obtain the file but you can load it off of your server using a simple XMLHttpRequest. Here is a useful resource for that: Using XMLHttpRequest

Excerpt from the link with modifications:

var treeData;

var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.open("get", "yourFile.txt", true);
oReq.send();

function reqListener(e) {
    treeData = JSON.parse(this.responseText);
}

Update based on comments below:

You cannot load a file with JSON.parse(). This function is only able to convert an existing string into an object (if content is in valid JSON format).

You need to:

  1. Load the file from your server to a variable using for example AJAX (as shown). You cannot use a local file path due to security reasons. Set up a local server to run your page in such as the free light-weight Mongoose web server. This will let you point the root to your local folder, then load your page using http://localhost/

  2. When file has been loaded you can pass the content to the JSON.parse() function. The example above show the whole process. Just replace links with actual ones in your code.

(PS: if you wanted a jQuery solution remember to tag your question with the jQuery tag)

  • var treeData = JSON.parse('C:\Users\Bubee\Desktop\Paser Tree\codepen_DjKIa\test.json'); it doesn't work – user3248233 Jan 30 '14 at 07:38
  • @user3248233 you can't use a local file, it has to be on your server (security related). You can set up a simple local server to test such as f.ex. [Mongoose](https://code.google.com/p/mongoose/). That allows you to use http links which you need here (ie. `http://localhost/.../test.json`, replace with an actual link). Also, you can't *load* a file with JSON.parse. You need to load the file using the ajax call as shown in the answer, then pass the result to JSON.parse. Hope this helps.- –  Jan 30 '14 at 07:39
  • In some cases, it is also useful to set the type of the file, for example `oReq.overrideMimeType("text/plain");` If you don't do this, than sometimes will occur `not well-formed` error. – gabor aron Oct 26 '19 at 15:05
9

How about $.getJSON

$.getJSON( "yourjsonfile.json", function( data ) {  
    console.log( "JSON Data: " + data);
    $.each( data, function( key, val ) {
        console.log(key + "value:: " + val );
    });
});

Ref: http://api.jquery.com/jquery.getjson/

Krish R
  • 22,583
  • 7
  • 50
  • 59
0

Do an AJAX request of your JSON file, then use JSON.parse to add the result into treeData.

var treeData = JSON.parse(ajaxFunction('jsonfile.php'));

Something to that effect... (it will vary depending on your AJAX function)

CJT3
  • 2,788
  • 7
  • 30
  • 45
0

If someone is using GULP then here is how you can solve:

var gulp = require('gulp'),
    concat = require('gulp-concat'),
    insert = require('gulp-insert');

gulp.task('jsonConcat', function() {
  return gulp.src(['path/to/json/your-file.json'])
    .pipe(insert.prepend('treeData = '))
    .pipe(insert.append(';'))
    .pipe(concat('final-result.js'))
    .pipe(gulp.dest('path/to/destination/'));
});
Syed
  • 15,657
  • 13
  • 120
  • 154