0

this is the contents of a file named menu.json:

 { "name":"John", "city":"New York"} 

I want to use jquery to parse the json file into the console of Chrome

var res = $.getJSON("menu.json", function() {}) .done(function() { var obj = $.parseJSON(res); console.log(obj.name); }); 

For some reason, Chrome is saying "Uncaught SyntaxError: Unexpected token o in JSON at position 1"

I'm running the page in MAMP and in the network tab, I am able to see the json file that's been loaded correctly. Why is this error occurring. Any help is much appreciated!

1
  • getJSON parses the response before it is passed to the success callback. You don't have to parse it. Also res in your snippet is the promise returned from the getJSON call so that doesn't make sense that you are trying to parse that anyway Commented May 8, 2018 at 21:55

2 Answers 2

2

You're trying to decode an object, not a JSON string.

The thing you're trying to decode is being serialized before it gets passed to the JSON decoder as [object Object], hence the o at index 1.

Go back to the getJSON docs and you'll see you're not setting up your callback correctly. The return value you're storing in res is not what you think it is. You need to collect an argument to your callback function -- this is where your decoded response will be.

This should get you on the right lines:

$.getJSON("menu.json") .done(function(obj) { console.log(obj.name); }); 
Sign up to request clarification or add additional context in comments.

Comments

0

The data will already be parsed. Just accept the response in as an input to the done callback.

var url = 'https://cdn.rawgit.com/taplar/taplar-hiddenworld/b69ca458/src/assets/jsons/potions.json' $.getJSON(url).done(function(data){ console.log(data); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.