If I have a JSON
file named names.json with:
{"employees":[
{"firstName":"Anna","lastName":"Meyers"},
{"firstName":"Betty","lastName":"Layers"},
{"firstName":"Carl","lastName":"Louis"},
]}
How can I use its content in javascript?
If I have a JSON
file named names.json with:
{"employees":[
{"firstName":"Anna","lastName":"Meyers"},
{"firstName":"Betty","lastName":"Layers"},
{"firstName":"Carl","lastName":"Louis"},
]}
How can I use its content in javascript?
I know the answer was given a long time ago, but this result is showing in first position on google.
However I don't want to use jquery, so in vanilla JS , I found this quick tutorial cleaner than senornestor answer (it also allow to load files depending on a variable) :
and on your html file:
Your JSON file does not contain valid JSON. Try the following instead.
You should then see a response. Check out http://jsonlint.com/
For those sent here by Google after the fall of JQuery, use Fetch API
If you want to use PHP.
Optionally, use it async:
The PHP:
In the jQuery code, you should have the
employees
property.So it would be like this.
Of course you'll need that property for the non jQuery version too, but you'd need to parse the JSON response first.
Also keep in mind that
document.write
is destroying your entire page.If you're still having trouble, try the full
$.ajax
request instead of the$.getJSON
wrapper.http://api.jquery.com/jquery.ajax/
An example how to do this could be: