How to import data from JSON to JavaScript? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How to import data from JSON to JavaScript?

If i have JSON data on server and i want to import it to javascript, how to do that ? Any ideas?

31st Mar 2018, 5:38 PM
Dejan Francuz🥇
Dejan Francuz🥇 - avatar
4 Answers
+ 6
Parse the content of the file like this: var treeData = JSON.parse(fileContent); You don't describe how you obtain the file but you can load it off of your server using a simple XMLHttpRequest. Here is a useful resource for that: Using XMLHttpRequest https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest Excerpt from the link with modifications: var treeData; var oReq = new XMLHttpRequest(); oReq.onload = reqListener; oReq.open("get", "yourFile.txt", true); oReq.send(); function reqListener(e) { treeData = JSON.parse(this.responseText); } Update based on comments below: You cannot load a file with JSON.parse(). This function is only able to convert an existing string into an object (if content is in valid JSON format). You need to: Load the file from your server to a variable using for example AJAX (as shown). You cannot use a local file path due to security reasons. Set up a local server to run your page in such as the free light-weight Mongoose web server. https://code.google.com/p/mongoose/ This will let you point the root to your local folder, then load your page using http://localhost/ When file has been loaded you can pass the content to the JSON.parse() function. The example above show the whole process. Just replace links with actual ones in your code. (PS: if you wanted a jQuery solution remember to tag your question with the jQuery tag) more: https://stackoverflow.com/questions/14484613/load-local-json-file-into-variable
31st Mar 2018, 7:25 PM
Baraa AB
Baraa AB - avatar
+ 6
json is json not javascript. You can parse json data with any language.
31st Mar 2018, 6:57 PM
Toni Isotalo
Toni Isotalo - avatar
+ 4
JSON is javascript, so you just need to retrieve the script with a http request, which will come as a string, and then you can parse it into a JSON object. https://www.w3schools.com/js/js_json_parse.asp
31st Mar 2018, 5:58 PM
ChaoticDawg
ChaoticDawg - avatar
+ 4
Sorry, I missed the word basically, but you're correct they technicaly are not the same thing. I was simply referring to the relationship between a javascript object and JSON. I.E. { "foo": "bar" } vs let obj = { "foo": "bar" }
31st Mar 2018, 7:09 PM
ChaoticDawg
ChaoticDawg - avatar