[英]How to parse a JSON file in Javascript?
I have a JSON file which contains the following: 我有一个包含以下内容的JSON文件:
[
{
“name”: “Joshia \”Placement\” Fonz”,
“color”: “white”
},
{
"name": “Trin Brin”,
“color”: “black”
},
{
“name”: “Su Et”,
“color”: “yellow”
}
]
And I would like to parse it to use the array and objects for the application. 我想解析它以将数组和对象用于应用程序。 So
'./students.json'
being the path for the JSON file, I attempted JSON.parse('./students.json')
but got an error Uncaught SyntaxError: Unexpected token . in JSON at position 0
所以,
'./students.json'
正在为JSON文件的路径,我试图JSON.parse('./students.json')
但得到了一个错误Uncaught SyntaxError: Unexpected token . in JSON at position 0
Uncaught SyntaxError: Unexpected token . in JSON at position 0
, and tried JSON.stringify('./students.json')
but it simply returned me the exact string of the path './students.json'
. Uncaught SyntaxError: Unexpected token . in JSON at position 0
,并尝试了JSON.stringify('./students.json')
但它只是向我返回了路径'./students.json'
的确切字符串。
So can I parse the JSON file in Javascript to use the array? 那么我可以解析Javascript中的JSON文件以使用数组吗?
Thank you 谢谢
You should use an ajax
request for that, jQuery
( $
) provides an abstraction for XHR
. 您应该为此使用
ajax
请求, jQuery
( $
)为XHR
提供了抽象。
$.get("./students.json", function(data){
//success callback
// data is the json you requested already parsed
}, "json");
Is the fastest way to achieve your goal, as long as by default client side is not able to read a file from the server even if there are file
API for client-side file reading but I guess that in this case it may provide you more problems than it actually solve. 这是达到目标的最快方法,只要默认情况下,即使有用于客户端文件读取的
file
API,客户端也无法从服务器读取文件,但我想在这种情况下,它可能会为您提供更多信息比实际解决的问题。
That's because you are parsing the string './students.json' not what is inside the file. 那是因为您正在解析字符串'./students.json'而不是文件内部的内容。 You should open the file and then take the info.
您应该打开文件,然后获取信息。 You could use this example to read the file https://stackoverflow.com/a/14446538/5334265 .
您可以使用此示例读取文件https://stackoverflow.com/a/14446538/5334265 。 Then use JSON.parse to the content.
然后使用JSON.parse来显示内容。
JSON是一种实用的javascript,因此您只需将其添加到页面即可:
<script language="JavaScript" type="text/javascript" src="./students.json"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.