In Chrome use JSONView or Firefox use JSONView
Answer from Vodun on Stack Overflowjavascript - View JSON file in Browser - Stack Overflow
How to read an external local JSON file in JavaScript? - Stack Overflow
execute a javascript code inside a json object? - Stack Overflow
javascript - Browser-native JSON support (window.JSON) - Stack Overflow
Videos
In Chrome use JSONView or Firefox use JSONView
If you don't want to install extensions, you can simply prepend the URL with view-source:, e.g. view-source:http://content.dimestore.com/prod/survey_data/4535/4535.json. This usually works in Firefox and Chrome (will still offer to download the file however if Content-Disposition: attachment header is present).
For reading the external Local JSON file (data.json) using javascript, first create your data.json file:
data = '[{"name" : "Ashwin", "age" : "20"},{"name" : "Abhinandan", "age" : "20"}]';
Then,
Mention the path of the json file in the script source along with the javascript file
<script type="text/javascript" src="data.json"></script> <script type="text/javascript" src="javascript.js"></script>Get the Object from the json file
var mydata = JSON.parse(data); alert(mydata[0].name); alert(mydata[0].age); alert(mydata[1].name); alert(mydata[1].age);
The loading of a .json file from a hard disk is an asynchronous operation, and thus it needs to specify a callback function to execute after the file is loaded.
function readTextFile(file, callback) {
var rawFile = new XMLHttpRequest();
rawFile.overrideMimeType("application/json");
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4 && rawFile.status == "200") {
callback(rawFile.responseText);
}
}
rawFile.send(null);
}
//usage:
readTextFile("/Users/Documents/workspace/test.json", function(text){
var data = JSON.parse(text);
console.log(data);
});
This function also works for loading a .html or .txt files, by overriding the mime type parameter to "text/html", "text/plain", etc.
No.
First of all, your example isn't valid JSON. Try it out at JSON validator.
Second of all, JSON is a data exchange standard and when properly parsed, any text that inside of it that is some code will not be executed.
Read on JSON security issues.
Rule of thumb: don't use JavaScript eval function, rather use a ready made parser such as Douglas Crockford's JSON evaluator.
This would not be JSON anymore. But you can post-process the parsed JSON:
json.some_code = eval(json.some_code);
However this may be dangerous (script injection, etc).
So, if you can, do this instead:
json = { key1 : "val1", key2: "val2", elem: "someid", html:"test" };
document.getElementById(json.elem).innerHTML=json.html;
All modern browsers support native JSON encoding/decoding (Internet Explorer 8+, Firefox 3.1+, Safari 4+, and Chrome 3+). Basically, JSON.parse(str) will parse the JSON string in str and return an object, and JSON.stringify(obj) will return the JSON representation of the object obj.
More details on the MDN article.
jQuery-1.7.1.js - 555 line...
parseJSON: function( data ) {
if ( typeof data !== "string" || !data ) {
return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return ( new Function( "return " + data ) )();
}
jQuery.error( "Invalid JSON: " + data );
}
rvalidchars = /^[\],:{}\s]*$/,
rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
I have a simple html file:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="Dashboard"> <title>Dashboard</title> </head> <body> <script type="text/javascript" src="update.js"></script> <h1>Price of Stocks:</h1> <h2 id="ap">Apple: </h2> <h2 id="ts">Tesla: </h2> <button onclick="updatePrice();">update</button> </body> </html>
update.js looks like this:
const src = require("./prices.json");
function updatePrice() {
document.getElementById("ap").innerHTML = "Apple: " + src.Apple.price;
document.getElementById("ts").innerHTML = "Tesla: " + src.Tesla.price;
};The json file is as follows: (prices are arbitrarily entered right now)
{
"Apple": {
"price": 10.0
},
"Tesla": {
"price": 10.0
}
}This html file is not on a webserver and loads directly from C://, the prices.json and update.js are located in the same directory as index.html
The main issue here is that I cannot use require outside of node.js, I know I can use browserify, but surely there is a better way to read data from that json file.
$.getJSON is asynchronous so you should do:
$.getJSON("test.json", function(json) {
console.log(json); // this will show the info it in firebug console
});
I had the same need (to test my angularjs app), and the only way I found is to use require.js:
var json = require('./data.json'); //(with path)
note: the file is loaded once, further calls will use the cache.
More on reading files with nodejs: http://docs.nodejitsu.com/articles/file-system/how-to-read-files-in-nodejs
require.js: http://requirejs.org/
I want to save some numbers from a small program in a local JSON file.
Example:
const increaseButton = document.getElementById("increase-button")
const numberField = document.getElementById("count-field")
let myNum = 0
let myArray = []
increaseButton.addEventListener("click", increaseNum)
function increaseNum() {
myNum++
numberField.innerText = myNum
myArray.pop()
myArray.push(myNum)
let jsonString = JSON.stringify(Object.assign({}, myArray))
console.log(jsonString)
}
The jsonString should be saved in a local file "myjson.json".
Goal: If I increase the number with the increaseButton, the new value should be saved in the "myjson.json" file:
{
"numbers": {
"0":1}
}The only option I found was with node.js plugin "fs" and a lot of code. Couldn't it be easier?