0

I am trying to read the contents of a JSON file in Javascript, but I can't get any method working. The JSON is included in a script tag:
<script id="data" type="application/json" src="https://example.com/file.js"></script>

The file contains just JSON, but is not in my domain. More specifically, I'm trying to get the data from the Gravatar Profile API. The format is like in this example: http://es.gravatar.com/205e460b479e2e5b48aec07710c08d50.json?callback=test
The thing is, I can read the content once, inside a function, thanks to the callback parameter, but I need to read it again in another function.

How shoud I do it?
Thanks in advance.

Berna
  • 131
  • 1
  • 3
  • 14

2 Answers2

0

The JSON isn't included. JSON is not a script and browsers have no idea what to do when you try to load it using a script element. All that script element is doing is sitting in the DOM. Therefore:

  1. Find the script element by its id
  2. Get the src attribute from it
  3. Use XMLHttpRequest to request the data
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

In case you have created your file, put your json string inside a variable so you can have access to this variable from other scripts. When you have done that you can just use jQuery.parseJSON to retrieve the object. http://api.jquery.com/jquery.parsejson/

In case the file is only json content you are getting from a server or any other source instead of adding it by the script tag I would recommend to make an AJAX request to get the content. http://api.jquery.com/jquery.ajax/

Nuxy
  • 386
  • 1
  • 2
  • 17