【问题标题】:forEach is Not a Function Error in JQuery from JSON arrayforEach 不是来自 JSON 数组的 JQuery 中的函数错误
【发布时间】:2020-05-03 15:46:12
【问题描述】:

我正在访问 JSON 字符串中的元素,但我收到了

的错误

jQuery.Deferred 异常:Object.keys(...).Each 不是函数success@http....

这是我的代码:

response =JSON.stringify('[{"file": "app.dll", "fields": {"name": "Misc App", "rank": 1}}]');
response = JSON.parse(response);
console.log(response);

response.forEach(function(element){
    console.log(element);
});

演示如何显示数组中元素的名称和值的奖励积分!

【问题讨论】:

  • 重新标记为 JS,因为问题中没有 jQuery
  • stringify 一个字符串。猜猜结果数据类型是什么? ;)

标签: javascript arrays json foreach


【解决方案1】:

很多东西都可以用 Javascript 序列化,包括字符串。例如,如果你字符串化:

const foo = 'foo';
JSON.stringify(foo);

你得到

"foo"

在这里,因为您以相同的方式对字符串进行字符串化:

response =JSON.stringify('[{"file": "app.dll", "fields": {"name": "Misc App", "rank": 1}}]');

稍后解析时,您会按预期返回原始字符串

要么一开始就不要把它串起来:

let response = '[{"file": "app.dll", "fields": {"name": "Misc App", "rank": 1}}]';
response = JSON.parse(response);
console.log(response);

response.forEach(function(element){
    console.log(element);
});

或者,如果你真的需要,解析它两次

let response = JSON.stringify('[{"file": "app.dll", "fields": {"name": "Misc App", "rank": 1}}]');
response = JSON.parse(JSON.parse(response));
console.log(response);

response.forEach(function(element){
    console.log(element);
});

(但这是一个非常奇怪的解决方案 - 最好不要一开始就对字符串进行字符串化,因为它已经是可解析的 JSON 格式)

【讨论】:

    猜你喜欢
    • 2016-06-28
    • 2017-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 2018-04-04
    • 1970-01-01
    • 2023-03-05
    相关资源
    最近更新 更多