0

I have a json file which is generated by Java component and I trying to parse that json file via Javascript. But if I use this code:

var foo = JSON.parse('js/test.json');

I am getting this error:

Uncaught SyntaxError: Unexpected token :

Strange is I am generating this JSON via JSONObject which of-course produces valid JSON string. I tried with few online validators, and all of them are showing as a valid json. But javascript is throwing me this error.

Can anyone guide me to resolve this error? I searched many questions on SO but no luck. I posted my json here

7
  • 1
    Is 'js/test.json' a URL? Because that doesn't look like a valid JSON expression to me. Commented Nov 27, 2013 at 6:28
  • @ElliottFrisch, it's a JSON file under js folder in web app. Commented Nov 27, 2013 at 6:29
  • 2
    JSON.parse takes a string of JSON, not a filename/url. Commented Nov 27, 2013 at 6:29
  • @Xymostech, then how do I read that from file? Can you please guide me? Commented Nov 27, 2013 at 6:30
  • Are you using jQuery? Commented Nov 27, 2013 at 6:31

2 Answers 2

1

JSON.parse parses JSON string expressions into javascript objects. I suggest you make an ajax call to js/test.json and then I think your parse will work.

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

Comments

0

Give this a try

var httpRequest;
if (window.XMLHttpRequest) {
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { 
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}

httpRequest.onload = getJSON;
httpRequest.open('get', 'js/test.json', true);
httpRequest.responseType = "json";
httpRequest.send();


function getJSON(){var foo=httpRequest.response;}

Comments

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.