简体   繁体   English

如何在JavaScript中没有jQuery的情况下读取.json文件?

[英]How can I read a .json file without jQuery in JavaScript?

I am only asking the question because I've spent the last 2 days probably reading through countless other questions that are similar and tutorials and still can't get this to work. 我之所以只问这个问题,是因为我花了最后两天阅读了无数其他类似的问题和教程,但仍然无法解决这个问题。

I have a local .json file that I want to load up and parse with JavaScript. 我有一个本地.json文件,我想加载并使用JavaScript进行解析。 The file is called 'fakeData.json'. 该文件称为“ fakeData.json”。 Its format is as such: 其格式如下:

{"UIGroup": {"Parent": null, "Type": "public"}}

I'm using this to try to load the file: 我正在使用它来尝试加载文件:

<script src="fakeData.json"></script>

I am using this to try to parse the file: 我正在使用它尝试解析文件:

var jsonData = JSON.parse('fakeData.json');

I am getting these errors: 我收到这些错误:

Uncaught SyntaxError: Unexpected token : fakeData.json:1
Uncaught SyntaxError: Unexpected token ILLEGAL : planetPage.html:11

May someone please help me, thanks. 有人可以帮我,谢谢。

If you want it as simple as it gets, then I would prefix your json content with 如果您希望它变得尽可能简单,那么我将在您的json内容前添加前缀

var jsonData = {"UIGroup": {"Parent": null, "Type": "public"}}....

which turns your file into a valid js file and then load it with 这会将您的文件转换为有效的js文件,然后使用

<script src="fakeData.json.js"></script>

after that, jsonData will have the required content because of literal object notation. 之后,由于文字对象表示法,jsonData将具有必需的内容。

There is no way that you can load a json file into your page otherwise without ajax/httprequest. 如果没有ajax / httprequest,则无法将json文件加载到页面中。

You need to get the JSON text into a string variable before you can parse it. 您需要先将JSON文本转换为字符串变量,然后才能对其进行解析。

This is generally achieved using the XMLHttpRequest object . 通常使用XMLHttpRequest对象来实现。

<script src="fakeData.json"></script> will attempt to parse the JSON as JavaScript. <script src="fakeData.json"></script>将尝试将JSON解析为JavaScript。 This will either throw an error (as it does in your case) or create a data structure and then immediately discard it as it isn't assigned there. 这将抛出一个错误(如您的情况),或者创建一个数据结构,然后立即将其丢弃(因为未分配该结构)。

var jsonData;
function reqListener () {
  jsonData = JSON.parse(this.responseText);
  console.log(jsonData);
};

var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.open("get", "fakeData.json", true);
oReq.send();

If you want to keep it all inline, with a JSON string, and access the object directly you could do something like this: 如果要使用JSON字符串将其全部内联,并直接访问对象,则可以执行以下操作:

// copy all the JSON text from the file an keep store it in a local string variable. 
var jsonString = '{ "UIGroup": { "Parent": null, "Type": "public" }}';

// parse the string into a JavaScript object
var jsonObj = JSON.parse(jsonString);

// access the object as you usually would
alert(jsonObj.UIGroup.Type);

Fiddle 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM