Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON Parse File Path

Tags:

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.

like image 248
jagger Avatar asked Jun 07 '13 19:06

jagger


People also ask

What is JSON parse?

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.

Is JSON Parsable JavaScript?

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.

How do you parse a JSON file in Python?

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.


1 Answers

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]); 
like image 52
karthikr Avatar answered Nov 01 '22 19:11

karthikr