8

My json file looks like this

{
    "Persons": {
        "Name" : "e",
        "Name2": "e",
        "Id": "4700"
    }, [...]
}

How does my code looks like to parse/load this local json file into a html file. I tried everything out but none of them worked.

17
  • 1
    You need to make an AJAX GET request to load data. Then you would use JSON.parse to parse text loaded content into object data. Commented Dec 8, 2014 at 14:38
  • What are you using to retrieve the data? An attempt should help everyone out. Commented Dec 8, 2014 at 14:39
  • @dfsq AJAX GET of the local file will fails in Chrome. Commented Dec 8, 2014 at 14:40
  • @lexicore it should work if running a local webserver. Commented Dec 8, 2014 at 14:41
  • 2
    @brbcoding I'd argue that "load a resource using a local webserver" is not the same as "load a local file". Commented Dec 8, 2014 at 14:42

1 Answer 1

6

Here's an example from (http://youmightnotneedjquery.com/)

request = new XMLHttpRequest();
request.open('GET', '/my/url', true);

request.onload = function() {
  if (request.status >= 200 && request.status < 400){
    // Success!
    data = JSON.parse(request.responseText);
  } else {
    // We reached our target server, but it returned an error

  }
};

request.onerror = function() {
  // There was a connection error of some sort
};

request.send();

Your data variable will then have accessible members like this:

alert(data.Persons.Name);

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

1 Comment

Depends where the file is in relation to the file you're working on. If it's in the "data" folder then yes. As a pointer for further help in the future, definitely include more details, like the location of the data.json file, and some of the code you've tried to use.

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.