如何访问JSON元素-"JavaScript中名称中的字符

How to access JSON element which has "-" character in the name in JavaScript

本文关键字:JavaScript quot 字符 何访问 访问 元素 JSON      更新时间:2023-09-26

我有一个JSON对象,它返回以下值。

{
   "articles":[
      {
         "paper-id":"id",
         "paper-id-type":"type",
         "title":"title",
         "url":"url",
         "abstract":"abs",
         "date":"date",
         "publication-forum":"forum",
         "publication-forum-type":"type",
         "authors":"auth",
         "keywords":"key1,key2"
      }
   }

我试图通过JavaScript访问这些结果。首先,我创建了一个数组,并将这些结果分配给该数组。

数组(命名文章)对象的内容如下所示;

abstract: "xxx"
authors: "yyy"
date: "1111"
keywords: "key1, key2"
paper-id: "abc"
paper-id-type: "xxx"
publication-forum: "yyy"
publication-forum-type: "zzz"
title: "www"
url: "url"

然后我尝试使用格式访问这些元素中的每个值

articles[0]["abstract"]

它适用于没有"-"字符的元素。所以当我试图提取纸张id时;

articles[0]["paper-id"]

我要error [Exception: SyntaxError: Unexpected token []

有人知道如何解决这个问题吗?

问题是因为您忘记关闭JSON 中的[]{}

JSON应该看起来像这个

{
   "articles":[
      {
         "paper-id":"id",
         "paper-id-type":"type",
         "title":"title",
         "url":"url",
         "abstract":"abs",
         "date":"date",
         "publication-forum":"forum",
         "publication-forum-type":"type",
         "authors":"auth",
         "keywords":"key1,key2"
      }]
}
abc = {
    "articles": [{
            "paper-id": "id",
            "paper-id-type": "type",
            "title": "title",
            "url": "url",
            "abstract": "abs",
            "date": "date",
            "publication-forum": "forum",
            "publication-forum-type": "type",
            "authors": "auth",
            "keywords": "key1,key2"
        }
    ]
};
for (i in abc['articles'][0]) {
    console.log(abc['articles'][0][i]);
}