Richard
Richard

Reputation: 437

How to load JSON basic

I posted this question to understand why this works with Gravatar and not in a typical production environment. The answer was simple but something I overlooked because I am new to working with JSON and assumed the issue was my understanding of it. This forum was absolutely no help in understanding that Gravatar's back-end is simply using server side script to output Javascript when the callback is used and plain JSON when only the URL to the JSON is accessed. Thus making this script work, because it is script being output.

Although the first part of the question was responded to, and helpful, the later part of discovering how this was possible with Gravatar was completely ignored. Because only half of this question was commented on, I would like this thread removed. Thanks.


I have been working with some JSON projects and I continue to run into an error, time and again.

Uncaught SyntaxError: Unexpected token :

The index.html is as follows

<!doctype html>
<html>
  <head>
    <title>JSON</title>
    <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"/>
    <meta http-equiv="content-language" content="es"/>
    <script type="application/javascript" async="true" defer="true" src="script.js"></script>
    <script type="application/javascript" async="true" defer="true" src="flag.json?callback=pFlag"></script>
  </head>
  <body>
  </body>
</html>

script.js

function pFlag(data){
  console.log(data);
}

flag.json

{"flag":{"color":"green"}}

I have another project using these same principle that does not produce this error.

http://lib.richardkentgates.com/gravacon/

What gives?

Upvotes: 0

Views: 70

Answers (2)

elixenide
elixenide

Reputation: 44833

The problem is in this line:

<script type="application/javascript" async="true" defer="true" src="flag.json?callback=pFlag"></script>

JSON is based on a subset of JavaScript, but it is not actually JavaScript. You cannot call your .json file as a script (i.e., using a <script> tag). Instead, you should load it using AJAX.

Upvotes: 1

Marc B
Marc B

Reputation: 360652

Never going to work like that. you're loading your flag.json as an external script, which means the file has to contain valid JS code. What you have is not actual code, it's just a JS value definition. External scripts must basically be the contents of a <script> tag block, WITHOUT the script tag. e.g

var foo = {"flag":{"color":"green"}};

would work.

Given the callback business in your url, you're probably trying to do a JSONP-type request, which means flag.json should actually contain this:

pFlag({"flag":{"color":"green"}})

Upvotes: 4

Related Questions