简体   繁体   English

用javascript读取本地JSON文件

[英]Read local JSON file in javascript

I want to load json file in javascript.我想在 javascript 中加载 json 文件。 I found a link below.我在下面找到了一个链接。 http://www.askyb.com/javascript/load-json-file-locally-by-js-without-jquery/ http://www.askyb.com/javascript/load-json-file-locally-by-js-without-jquery/

test1.json测试1.json

data = '[{"name" : "Harry","age": 32.12}]';

test2.json测试2.json

data = '[
    {
        "name" : "Harry",
        "age": "32"
    }
]';

The code in the link above works with test1.json, but with test2.json, I have got error below.上面链接中的代码适用于 test1.json,但使用 test2.json,我在下面遇到错误。

Uncaught SyntaxError: Invalid or unexpected token
Uncaught ReferenceError: data is not defined
    at load (myscript.js:2)
    at onload (test.html:8)

What's the reason?什么原因?

myscript.js我的脚本.js

function load() {
    var mydata = JSON.parse(data);
    alert(mydata[0].name);
}

index.html索引.html

<!doctype html>
<html>
    <head>
        <title>Load JSON</title>
        <script type="text/javascript" src="test1.json"></script>
        <script type="text/javascript" src="myscript.js"></script>
    </head>
    <body onload="load()">
    </body>
</html>

If you are going to have a varaible span multiple lines, you need to use back ticks not single quotes如果您打算让变量跨多行,则需要使用反引号而不是单引号

 let data1 = '[{"name" : "Harry","age": 32.12}]'; let data2 = `[ { "name" : "Harry", "age": "32" } ]`; let JSONdata1 = JSON.parse(data1); let JSONdata2 = JSON.parse(data2); console.log(JSONdata1 ); console.log(JSONdata2 );

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

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