【问题标题】:Iterating over list of JSON in Javascript from MySQL从 MySQL 迭代 Javascript 中的 JSON 列表
【发布时间】:2021-08-30 21:55:25
【问题描述】:

我的 JSON 是这样存储在 MySQL 中的......

{'profile':'sweet', 'count':38},{'profile':'bitter', 'count':31},{'profile':'green', 'count':22}

当它作为 JSON 从 Express 返回时,它看起来像这样......

[{"JSON":"{'profile':'sweet', 'count':38},{'profile':'bitter', 'count':31},{'profile':'green', 'count':22}"}]

根据 JSONLint.com,这是有效的 JSON

让我感到震惊的是在 HTML javascript 中对其进行迭代...

我在 Javascript 中有这个 ....

   fProfiles_JSON = JSON.parse(xhr.responseText);
   console.log('Type of '+ typeof fProfiles_JSON); //yields "object"
   console.log('My object', fProfiles_JSON);
   console.log('LENGTH ', fProfiles_JSON.length); // Yields "1"

我知道我必须以某种方式迭代此对象类型以获取“配置文件”和“计数”值,但老实说,我不确定如何因为长度值为“1”。我知道这可能很简单,我只是没有看到它。有人能指出我正确的方向吗?

【问题讨论】:

  • 这不是有效的 JSON。如果你有多个对象,它们需要放在一个数组中。
  • 如果您使用 console.log 记录 fProfiles_JSON 会是什么样子?
  • 它是有效的 JSON,因为它被打包成一个字符串......但显然是一个字符串。
  • 你能告诉我们xhr - 它返回了什么?
  • xhr.responseText ?那到底是什么?

标签: javascript json express


【解决方案1】:
var obj = [{"JSON":"{'profile':'sweet', 'count':38},{'profile':'bitter', 'count':31},{'profile':'green', 'count':22}"}]

// in this case we have to extract the string:
var string = obj[0]["JSON"]
var fProfiles = JSON.parse("[" + string + "]");
// as @Barmar pointed out, the string's content is not valid JSON.
// so we add at beginning and end square brackets to get a list
// of objects.
FProfiles.length // should be 3
// and you can access the `count` and `profile` attributes.

【讨论】:

  • 金光进太棒了!解决了我的问题。非常感谢您解释为什么 JSONLint.com 认为它是有效的。
  • @JaneWilkie 欢迎您! ;) - 他看到有问题是对的。但他是不对的,因为它完全无效。 (因为它是一个字符串,所以它是有效的 - 但内容不是有效的 JSON ;))。
  • 这不适用于嵌套字符串周围的单引号。
【解决方案2】:

Json 不接受单引号,所以必须替换它们

//xhr.responseText contents simulated with var
resp = "[{\"JSON\":\"{'profile':'sweet', 'count':38},{'profile':'bitter', 'count':31},{'profile':'green', 'count':22}\"}]";

j = JSON.parse(resp);
inner = j[0]['JSON'].replaceAll("'","\"");

objs = JSON.parse("[" + inner +"]");
objs[0]

结果:

Object { profile: "sweet", count: 38 }

正如@barmar 指出的那样,使用自定义解析器“修复”json 总是有风险的。
更好的尝试可能是用更具体的正则表达式替换单引号

# added possible 'key': 'value' at the end
resp = "[{\"JSON\":\"{'profile':'sweet', 'count':38},{'profile':'bitter', 'count':31},{'profile':'green', 'count':22},{'key99': 'value99'}\"}]";
j = JSON.parse(resp);

re3 = /[{]'/ig;
re4 = /'[}]/ig;
re1 = /'(, *|: *)'/ig;
re2 = /' *: *([0-9])/ig;
inner = j[0]['JSON'].replaceAll(re3,"{\"").replaceAll(re4, "\"}").replaceAll(re1, "\"$1\"").replaceAll(re2,"\":$1");
// "{\"profile\":\"sweet\", \"count\":38},{\"profile\":\"bitter\", \"count\":31},{\"profile\":\"green\", \"count\":22},{\"key99\": \"value99\"}"

objs = JSON.parse("[" + inner +"]");
// Array(3) [ {…}, {…}, {…} ]

【讨论】:

  • 如果有任何单引号应该按字面处理,这将不起作用。一般来说,“修复”损坏的 JSON 的临时方法并不可靠。问题应该从源头上解决。
猜你喜欢
  • 2012-01-28
  • 1970-01-01
  • 2012-09-13
  • 2016-08-03
  • 1970-01-01
  • 2020-12-07
  • 2011-05-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多