【问题标题】:How can I get JSON data and parse it to an Array in jquery? [duplicate]如何获取 JSON 数据并将其解析为 jquery 中的数组? [复制]
【发布时间】:2020-11-05 20:49:31
【问题描述】:

我正在尝试从服务器获取数据并对其进行解析,以便将其格式化为以 HTML 显示的内容

我在解析 JSON 文件中的数据时遇到问题

这是我的代码:

JS

    var AnnouncementsJSON
    $.get("data/announcements.json", function(data) {
        console.log(data)
        AnnouncementsJSON = $.parseJSON(data)
    });
    console.log(AnnouncementsJSON)

announcements.json


    {
    "announcements":[
        {
            "title":"This is the Announcement!",
            "subtitle":"This is going to be used as announcements",
            "link":"/somewhere.html"
        }
    ]
}

控制台/检查元素:

(index):189 {announcements: Array(1)}
VM976:1 Uncaught SyntaxError: Unexpected token o in JSON at position 1
    at Function.parse [as parseJSON] (<anonymous>)
    at Object.success ((index):190)
    at c (jquery.min.js:2)
    at Object.fireWith [as resolveWith] (jquery.min.js:2)
    at l (jquery.min.js:2)
    at XMLHttpRequest.<anonymous> (jquery.min.js:2)
(anonymous) @ (index):190
c @ jquery.min.js:2
fireWith @ jquery.min.js:2
l @ jquery.min.js:2
(anonymous) @ jquery.min.js:2
load (async)
send @ jquery.min.js:2
ajax @ jquery.min.js:2
S.<computed> @ jquery.min.js:2
(anonymous) @ (index):188

错误消息上方显示{Announcements: Array(1)},所以我知道我可以从浏览器访问 JSON 文件。另外,我导航到它并且能够访问它

【问题讨论】:

  • “Unexpected token o”几乎总是意味着你根本没有得到 JSON:打开你的开发工具,选择网络选项卡,重新运行你的 fetch 并查看你的'正在实际上回来。
  • "Unexpected token o" 通常在您尝试解析已经解析过的内容时出现。记录typeof data,如果是“对象”,jQuery 已经为你解析好了。

标签: javascript jquery json ajax


【解决方案1】:

我相信您正在寻找的解决方案是 JSON.parse,但我也认为此有效负载不需要 JSON.parse,因为它是作为对象出现的。 $.get 返回一个带有响应负载的对象。

【讨论】:

  • 我认为你是正确的,因为我在尝试这个例子时看到了同样的错误: var e = JSON.parse({thing:"test"}) 这个例子解析了一个对象,但它给出了一个错误, 因为它应该解析 JSON 字符串。
  • 也就是说,可以只做:AnnouncementsJSON = data;
  • @raddevus 你是对的! JSON.parse 需要一个字符串化的对象,所以它可以把它变成一个对象。与之相反的是 JSON.stringify ,它接受一个对象并将其转换为字符串。这对于将加密对象存储在本地存储中非常有用。
【解决方案2】:

您应该能够在不进行任何额外解析的情况下访问它。我认为您收到该错误是因为您正在尝试解析已解析的 json...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-28
    • 1970-01-01
    • 2021-08-08
    • 2023-04-11
    • 2017-07-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多