簡體   English   中英

如何訪問JavaScript名稱中帶有“-”字符的JSON元素

[英]How to access JSON element which has “-” character in the name in JavaScript

我有一個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]);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM