Loading local JSON file

2018-12-31 07:08发布

I'm trying to load a local JSON file but it won't work. Here is my JavaScript code (using jQuery:

var json = $.getJSON("test.json");
var data = eval("(" +json.responseText + ")");
document.write(data["a"]);

The test.json file:

{"a" : "b", "c" : "d"}

Nothing is displayed and Firebug tells me that data is undefined. In Firebug I can see json.responseText and it is good and valid, but it's strange when I copy the line:

 var data = eval("(" +json.responseText + ")");

in Firebug's console, it works and I can access data.

Anyone have a solution?

21条回答
忆尘夕之涩
2楼-- · 2018-12-31 08:04

What worked for me is the following:

Input:

http://ip_address//some_folder_name//render_output.html?relative/path/to/json/fie.json

Javascript Code:

<html>
<head>

<style>
pre {}
.string { color: green; }
.number { color: darkorange; }
.boolean { color: blue; }
.null { color: magenta; }
.key { color: red; }
</style>

<script>
function output(inp) {
    document.body.appendChild(document.createElement('pre')).innerHTML = inp;
}

function gethtmlcontents(){
    path = window.location.search.substr(1)
    var rawFile = new XMLHttpRequest();
    var my_file = rawFile.open("GET", path, true)  // Synchronous File Read
    //alert('Starting to read text')
    rawFile.onreadystatechange = function ()
    {
        //alert("I am here");
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                //alert(allText)
                var json_format = JSON.stringify(JSON.parse(allText), null, 8)
                //output(json_format)
                output(syntaxHighlight(json_format));
            }
        }
    }
    rawFile.send(null);
}

function syntaxHighlight(json) {
    json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
        var cls = 'number';
        if (/^"/.test(match)) {
            if (/:$/.test(match)) {
                cls = 'key';
            } else {
                cls = 'string';
            }
        } else if (/true|false/.test(match)) {
            cls = 'boolean';
        } else if (/null/.test(match)) {
            cls = 'null';
        }
        return '<span class="' + cls + '">' + match + '</span>';
    });
}

gethtmlcontents();
</script>
</head>
<body>
</body>
</html>
查看更多
公子世无双
3楼-- · 2018-12-31 08:05

In a more modern way, you can now use the Fetch API:

fetch("test.json")
  .then(response => response.json())
  .then(json => console.log(json));

All modern browsers support Fetch API. (Internet Explorer doesn't, but Edge does!)

source:

查看更多
冷夜・残月
4楼-- · 2018-12-31 08:05

In angular (or any other framework), you can load using http get I use it something like this:

this.http.get(<path_to_your_json_file))
 .success((data) => console.log(data));

Hope this helps.

查看更多
人气声优
5楼-- · 2018-12-31 08:05

json_str = String.raw`[{"name": "Jeeva"}, {"name": "Kumar"}]`;
obj = JSON.parse(json_str);

console.log(obj[0]["name"]);

I did this for my cordova app, like I created a new javascript file for the JSON and pasted the JSON data into String.raw then parse it with JSON.parse

查看更多
闭嘴吧你
6楼-- · 2018-12-31 08:07

I'm surprised import from es6 has not been mentioned (use with small files)

Ex: import test from './test.json'

webpack 2< uses the json-loader as default for .json files.

https://webpack.js.org/guides/migrating/#json-loader-is-not-required-anymore

For TypeScript:

import test from 'json-loader!./test.json';

TS2307 (TS) Cannot find module 'json-loader!./suburbs.json'

To get it working I had to declare the module first. I hope this will save a few hours for someone.

declare module "json-loader!*" {
  let json: any;
  export default json;
}

...

import test from 'json-loader!./test.json';

If I tried to omit loader from json-loader I got the following error from webpack:

BREAKING CHANGE: It's no longer allowed to omit the '-loader' suffix when using loaders. You need to specify 'json-loader' instead of 'json', see https://webpack.js.org/guides/migrating/#automatic-loader-module-name-extension-removed

查看更多
路过你的时光
7楼-- · 2018-12-31 08:10

Try is such way (but also please note that JavaScript don't have access to the client file system):

$.getJSON('test.json', function(data) {
  console.log(data);
});
查看更多
登录 后发表回答