代码之家  ›  专栏  ›  技术社区  ›  Stephen Frosty

用方括号语法解析python中的JSON问题

  •  -1
  • Stephen Frosty  · 技术社区  · 1 年前

    我收到了一个来自API的JSON,其中是英文词典中的单词定义。我需要解析数据并分离含义、定义和示例,但JSON文件存在一些语法问题。

    以下是接收到的单词Handsome的JSON示例:

    [   
      {
        "word": "handsome",
        "phonetic": "/ˈhæn.səm/",
        "phonetics": [
          {
            "text": "/ˈhæn.səm/",
            "audio": "https://api.dictionaryapi.dev/media/pronunciations/en/handsome-uk.mp3",
            "sourceUrl": "https://commons.wikimedia.org/w/index.php?curid=9021972",
            "license": {
              "name": "BY 3.0 US",
              "url": "https://creativecommons.org/licenses/by/3.0/us"
            }
          },
          {
            "text": "/ˈhæn.səm/",
            "audio": "https://api.dictionaryapi.dev/media/pronunciations/en/handsome-us.mp3",
            "sourceUrl": "https://commons.wikimedia.org/w/index.php?curid=1648256",
            "license": {
              "name": "BY-SA 3.0",
              "url": "https://creativecommons.org/licenses/by-sa/3.0"
            }
          }
        ],
        "meanings": [
          {
            "partOfSpeech": "verb",
            "definitions": [
              {
                "definition": "To render handsome.",
                "synonyms": [],
                "antonyms": []
              }
            ],
            "synonyms": [],
            "antonyms": []
          },
          {
            "partOfSpeech": "adjective",
            "definitions": [
              {
                "definition": "(of people, things, etc) Having a good appearance; good-looking.",
                "synonyms": [],
                "antonyms": [],
                "example": "a handsome garment, house, tree, or horse"
              },
              {
                "definition": "Good, appealing, appropriate.",
                "synonyms": [],
                "antonyms": []
              },
              {
                "definition": "Generous or noble in character.",
                "synonyms": [],
                "antonyms": [],
                "example": "Handsome is as handsome does."
              },
              {
                "definition": "Ample; moderately large.",
                "synonyms": [],
                "antonyms": [],
                "example": "a handsome salary"
              },
              {
                "definition": "(said of things and people) Dexterous; skillful.",
                "synonyms": [],
                "antonyms": []
              }
            ],
            "synonyms": [
              "hefty",
              "substantial",
              "good-looking",
              "pretty"
            ],
            "antonyms": []
          }
        ],
        "license": {
          "name": "CC BY-SA 3.0",
          "url": "https://creativecommons.org/licenses/by-sa/3.0"
        },
        "sourceUrls": [
          "https://en.wiktionary.org/wiki/handsome"
        ]   
       } 
     ]
    

    我写这段代码是为了加载数据并解析我想要的数据:

    data = [{"word":"handsome","phonetic":"/ˈhæn.səm/","phonetics":[{"text":"/ˈhæn.səm/","audio":"https://api.dictionaryapi.dev/media/pronunciations/en/handsome-uk.mp3","sourceUrl":"https://commons.wikimedia.org/w/index.php?curid=9021972","license":{"name":"BY 3.0 US","url":"https://creativecommons.org/licenses/by/3.0/us"}},{"text":"/ˈhæn.səm/","audio":"https://api.dictionaryapi.dev/media/pronunciations/en/handsome-us.mp3","sourceUrl":"https://commons.wikimedia.org/w/index.php?curid=1648256","license":{"name":"BY-SA 3.0","url":"https://creativecommons.org/licenses/by-sa/3.0"}}],"meanings":[{"partOfSpeech":"verb","definitions":[{"definition":"To render handsome.","synonyms":[],"antonyms":[]}],"synonyms":[],"antonyms":[]},{"partOfSpeech":"adjective","definitions":[{"definition":"(of people, things, etc) Having a good appearance; good-looking.","synonyms":[],"antonyms":[],"example":"a handsome garment, house, tree, or horse"},{"definition":"Good, appealing, appropriate.","synonyms":[],"antonyms":[]},{"definition":"Generous or noble in character.","synonyms":[],"antonyms":[],"example":"Handsome is as handsome does."},{"definition":"Ample; moderately large.","synonyms":[],"antonyms":[],"example":"a handsome salary"},{"definition":"(said of things and people) Dexterous; skillful.","synonyms":[],"antonyms":[]}],"synonyms":["hefty","substantial","good-looking","pretty"],"antonyms":[]}],"license":{"name":"CC BY-SA 3.0","url":"https://creativecommons.org/licenses/by-sa/3.0"},"sourceUrls":["https://en.wiktionary.org/wiki/handsome"]}]
    json_load = (json.loads(json_data))
    print(json_load['meanings'])
    

    此错误显示为: list indices must be integers or slices, not str 。如果我加上 [0] 到之前 [meanings] 问题解决了,但我不知道为什么要这么做: print(json_load[0]['meanings'])

    此外,我对内部级别也有同样的问题,无法解析数据。如果我删除JSON字符串开头和结尾的方括号,就不再需要 [0] 之前 【含义】

    我该怎么办?我需要在键之前添加数字吗?还是必须删除所有级别的方括号?

    5 回复  |  直到 1 年前
        1
  •  0
  •   AKX    1 年前

    API响应被包装在一个列表中,可能是因为它可能返回了多个结果。

    所以,是的,你会“在键之前加数字”(即访问数组的第零个成员);我只是要防止意外地得到多个结果,然后抓住第零个结果并继续努力。

    parsed_data = json.loads(json_data)
    if len(parsed_data) != 1:
        raise ValueError(f"Oops, got {len(parsed_data)} results!")
    first_definition = parsed_data[0]
    
    print(first_definition["word"], "(", first_definition["phonetic"], ")")
    
    for meaning in first_definition["meanings"]:
        print("*", meaning["partOfSpeech"])
        for defn in meaning["definitions"]:
            print("  *", defn["definition"])
        # ... etc...
    
        2
  •  0
  •   Tempestas Ludi    1 年前

    { [ 是单独的括号。第一个意思是“这里跟在一个‘对象’后面”,而第二个意思则是“这里跟着一个列表”。因此,如果粘贴从API获得的原始数据

    [
      {
        "word":"handsome",
        "phonetic":"/ˈhæn.səm/",
        "phonetics": [
          {
            "text":"/ˈhæn.səm/",
          
      "audio":"https://api.dictionaryapi.dev/media/pronunciations/en/handsome-uk.mp3",
            "sourceUrl":"https://commons.wikimedia.org/w/index.php?curid=9021972","license":{"name":"BY 3.0 US",
    ...
    

    您有一个列表,其中包含一个对象(或可能包含多个对象)。因此,最好的做法是使用数字索引 0 以获取列表中的第一个对象。或者更好的是,首先用 len(json_load)

        3
  •  0
  •   Nmeer Naji    1 年前

    您得到的错误意味着您正试图使用字符串键访问列表项(维奇是不可能的,您只能使用int索引访问列表)。

    • 您需要首先访问列表,然后才能访问内部json键值对

    • json中的任何内部列表也是如此,您需要首先指定索引,然后才能访问数据

        4
  •  0
  •   SIGHUP    1 年前

    如果您从某些API获取这些数据,那么很可能您将它们作为字符串获取。因此,让我们将您的数据制作成这样的字符串:

    js = '''[{"word":"handsome","phonetic":"/ˈhæn.səm/","phonetics":[{"text":"/ˈhæn.səm/","audio":"https://api.dictionaryapi.dev/media/pronunciations/en/handsome-uk.mp3","sourceUrl":"https://commons.wikimedia.org/w/index.php?curid=9021972","license":{"name":"BY 3.0 US","url":"https://creativecommons.org/licenses/by/3.0/us"}},{"text":"/ˈhæn.səm/","audio":"https://api.dictionaryapi.dev/media/pronunciations/en/handsome-us.mp3","sourceUrl":"https://commons.wikimedia.org/w/index.php?curid=1648256","license":{"name":"BY-SA 3.0","url":"https://creativecommons.org/licenses/by-sa/3.0"}}],"meanings":[{"partOfSpeech":"verb","definitions":[{"definition":"To render handsome.","synonyms":[],"antonyms":[]}],"synonyms":[],"antonyms":[]},{"partOfSpeech":"adjective","definitions":[{"definition":"(of people, things, etc) Having a good appearance; good-looking.","synonyms":[],"antonyms":[],"example":"a handsome garment, house, tree, or horse"},{"definition":"Good, appealing, appropriate.","synonyms":[],"antonyms":[]},{"definition":"Generous or noble in character.","synonyms":[],"antonyms":[],"example":"Handsome is as handsome does."},{"definition":"Ample; moderately large.","synonyms":[],"antonyms":[],"example":"a handsome salary"},{"definition":"(said of things and people) Dexterous; skillful.","synonyms":[],"antonyms":[]}],"synonyms":["hefty","substantial","good-looking","pretty"],"antonyms":[]}],"license":{"name":"CC BY-SA 3.0","url":"https://creativecommons.org/licenses/by-sa/3.0"},"sourceUrls":["https://en.wiktionary.org/wiki/handsome"]}]'''
    

    现在

    import json
    
    jlist = json.loads(js)
    
    print(jlist[0]["meanings"])
    

    然而,如果您已经处理了API响应,并且具有问题中所示的数据,那么它只是:

    js = [{"word":"handsome","phonetic":"/ˈhæn.səm/","phonetics":[{"text":"/ˈhæn.səm/","audio":"https://api.dictionaryapi.dev/media/pronunciations/en/handsome-uk.mp3","sourceUrl":"https://commons.wikimedia.org/w/index.php?curid=9021972","license":{"name":"BY 3.0 US","url":"https://creativecommons.org/licenses/by/3.0/us"}},{"text":"/ˈhæn.səm/","audio":"https://api.dictionaryapi.dev/media/pronunciations/en/handsome-us.mp3","sourceUrl":"https://commons.wikimedia.org/w/index.php?curid=1648256","license":{"name":"BY-SA 3.0","url":"https://creativecommons.org/licenses/by-sa/3.0"}}],"meanings":[{"partOfSpeech":"verb","definitions":[{"definition":"To render handsome.","synonyms":[],"antonyms":[]}],"synonyms":[],"antonyms":[]},{"partOfSpeech":"adjective","definitions":[{"definition":"(of people, things, etc) Having a good appearance; good-looking.","synonyms":[],"antonyms":[],"example":"a handsome garment, house, tree, or horse"},{"definition":"Good, appealing, appropriate.","synonyms":[],"antonyms":[]},{"definition":"Generous or noble in character.","synonyms":[],"antonyms":[],"example":"Handsome is as handsome does."},{"definition":"Ample; moderately large.","synonyms":[],"antonyms":[],"example":"a handsome salary"},{"definition":"(said of things and people) Dexterous; skillful.","synonyms":[],"antonyms":[]}],"synonyms":["hefty","substantial","good-looking","pretty"],"antonyms":[]}],"license":{"name":"CC BY-SA 3.0","url":"https://creativecommons.org/licenses/by-sa/3.0"},"sourceUrls":["https://en.wiktionary.org/wiki/handsome"]}]
    
    print(js[0]["meanings"])
    
        5
  •  0
  •   yusuf    1 年前

    由于您收到的数据是一个列表,因此您可以执行以下操作:

    print(type(data[0]))  # you have a dictionary now
    
    # assign it to a variable
    my_word = data[0] 
    
    # Check the meanings 
    print(my_word['meanings']) # this will print out your json