gpt4 book ai didi

javascript - 在javascript中解析具有特殊属性的json

转载 作者:行者123 更新时间:2023-11-28 12:32:49 24 4
gpt4 key购买 nike

我有一个如下的 json

"facet_counts": {
"facet_pivot": {
"title,host,content,anchor,id": [
{
"field": "title",
"value": "biglobe",
"count": 192
}
]
}}

像平常一样,我会像下面这样解析它:

var json = JSON.parse(xhr.responseText);
var field = json.facet_counts.facet_pivot.title,host,content,anchor,id[0].field;

但这是错误的。

你能告诉我如何解析属性“title,host,content,anchor,id”

最佳答案

有两种方法可以访问对象的属性:

  • obj.prop - 点表示法
  • obj['prop'] - 括号表示法

当 JS 解释器对属性名称的某些部分(在您的情况下为 ,)感到困惑时,您可以使用括号表示法来访问该属性:

var json = JSON.parse(xhr.responseText); 
var field = json.facet_counts.facet_pivot['title,host,content,anchor,id'][0].field;

This answer很好地总结了标识符命名限制:

An identifier must start with $, _, or any character in the Unicode categories “Uppercase letter (Lu)”, “Lowercase letter (Ll)”, “Titlecase letter (Lt)”, “Modifier letter (Lm)”, “Other letter (Lo)”, or “Letter number (Nl)”.

The rest of the string can contain the same characters, plus any U+200C zero width non-joiner characters, U+200D zero width joiner characters, and characters in the Unicode categories “Non-spacing mark (Mn)”, “Spacing combining mark (Mc)”, “Decimal digit number (Nd)”, or “Connector punctuation (Pc)”.

属性可以使用任何字符串作为名称,如果该字符串与上述描述不匹配,则只能使用方括号表示法来访问该属性。如果字符串确实与描述匹配,则方括号表示法和点表示法可以互换使用,但通常首选点表示法,因为它不太冗长。

关于javascript - 在javascript中解析具有特殊属性的json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20419955/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com