1

I am trying to show some JSON data on my website from external URL. When run the script I get this error from the chrome console:

Uncaught SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse ()

Javascript:

var json = $.getJSON("url");

var a = JSON.parse(json.responseText);

var result = a.query.results.rate;

document.write(result[0].Rate);

When I type console.log(result) in the console it returns undefined

JSON:

{
"query": {
    "count": 6,
    "created": "2016-12-21T19:18:22Z",
    "lang": "en-US",
    "diagnostics": {
        "url": [{
                "execution-start-time": "1",
                "execution-stop-time": "2",
                "execution-time": "1",
                "content": "url"
            }, {
                "execution-start-time": "5",
                // more of this
            ]

            "results": {
                "rate": [{
                        "id": "GBPUSD",
                        "Name": "GBP/USD",
                        "Rate": "1.2371",
                    },

                    {
                        "id": "GBPEUR",
                        // more of this
                    },

                }
            ]
        }

I can't make any changes on the JSON file, but I checked it and it is valid.

P.S. When I write the JavaScript code in the chrome console it works.

Thanks in advance.

Sᴀᴍ Onᴇᴌᴀ
  • 8,218
  • 8
  • 36
  • 58
hml
  • 23
  • 3

2 Answers2

3

Here's your problem:

var json = $.getJSON("url");

This is an asynchronous operation, you need to give it time to load, something like this would work:

$.getJSON("url").done(function(response) {
    var result = response.query.results.rate;
    document.write(result[0].Rate);
});
Tompina
  • 726
  • 1
  • 9
  • 25
0

It will work in the console if you execute each line with a bit of time in between AS response will have had time to complete and populate responseText. You need to rite the main code in a callback or promise chain after $.getJSON has completed.

Perhaps...

$.getJSON("url").then(function(data){
    var result = data.query.results.rate;
    document.write(result[0].Rate);
});
Billy Moon
  • 57,113
  • 24
  • 136
  • 237