I'm stuck trying to get the correct path to the local file. I have the following directories:
Resources -> data -> file.json js -> folder -> script.js html -> folder -> file1.html
I'm executing script.js
from file1.html
, with js code:
var answers = JSON.parse('../../data/file.json'); alert(answers);
But it doesn't work, even alert is not starting. What is wrong?
Also I've tried this:
function readJSON(file) { var request = new XMLHttpRequest(); request.open('GET', file, false); request.send(null); if (request.status == 200) return request.responseText; }; var temp = readJSON('../../data/file.json'); alert(temp);
Alert undefined in this case.
JSON parsing is the process of converting a JSON object in text format to a Javascript object that can be used inside a program. In Javascript, the standard way to do this is by using the method JSON. parse() , as the Javascript standard specifies.
JSON.parse() A common use of JSON is to exchange data to/from a web server. When receiving data from a web server, the data is always a string. Parse the data with JSON.parse() , and the data becomes a JavaScript object.
If you need to parse a JSON string that returns a dictionary, then you can use the json. loads() method. If you need to parse a JSON file that returns a dictionary, then you can use the json. load() method.
Since it is in the directory data/
, You need to do:
file path is '../../data/file.json'
$.getJSON('../../data/file.json', function(data) { alert(data); });
Pure JS:
var request = new XMLHttpRequest(); request.open("GET", "../../data/file.json", false); request.send(null) var my_JSON_object = JSON.parse(request.responseText); alert (my_JSON_object.result[0]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With