如何在Javascript中解析JSON文件

How to parse a JSON file in Javascript?

本文关键字:JSON 文件 Javascript      更新时间:2023-09-26

我有一个JSON文件,其中包含以下内容:

[
  {
    “name”: “Joshia '”Placement'” Fonz”,
    “color”: “white”
  },
  {
    "name": “Trin Brin”,
    “color”: “black”
  },
  {
    “name”: “Su Et”,
    “color”: “yellow”
  }
]

我想解析它,以便在应用程序中使用数组和对象。所以'./students.json'是JSON文件的路径,我尝试了JSON.parse('./students.json'),但得到了一个错误Uncaught SyntaxError: Unexpected token . in JSON at position 0,并尝试了JSON.stringify('./students.json'),但它只是返回了路径'./students.json'的确切字符串。

所以我可以解析JSON文件在Javascript中使用数组吗?

Thank you

这是因为您正在解析字符串'./students。Json不是文件内部的内容。你应该打开文件,然后获取信息。您可以使用这个示例读取文件https://stackoverflow.com/a/14446538/5334265。然后使用JSON。解析为内容

您应该使用ajax请求,jQuery ($)提供了XHR的抽象。

$.get("./students.json", function(data){
   //success callback
   // data is the json you requested already parsed
}, "json");

是最快的方式来实现你的目标,只要默认情况下客户端不能从服务器读取文件,即使有file API的客户端文件读取,但我想,在这种情况下,它可能会给你提供比它实际解决更多的问题。

文件

FileReader

JSON是一种合法的javascript,所以你可以在你的页面中添加:

<script language="JavaScript" type="text/javascript" src="./students.json"></script>