简体   繁体   中英

Python: Getting Keyerror when parsing JSON

I have just made a program to parse some data from an api. The api gives data back with a JSON format. When I try to parse it it gives me a key error

Traceback (most recent call last):
  File "test.py", line 20, in <module>
    print(parsed_json['plain'])
KeyError: 'plain'

This is the part of the code that matters (the rest is just for making the url, works perfectly fine)

response = urllib.request.urlopen(url2).read()
strr = str(response)


if "plain" in strr:
    parsed_json = json.loads(response.decode("UTF-8"))
    print(parsed_json['plain'])
elif "INVALID HASH" in strr:
    print("You have entered an invalid hash.")
elif "NOT FOUND" in strr:
    print("The hash is not found")
elif "LIMIT REACHED" in strr:
    print("You have reached the max requests per minute, please try again in one minute.")

I am trying to get the data in the plain field. Here is the output from the API:

{
  "REQUEST": "FOUND",
  "739c5b1cd5681e668f689aa66bcc254c": {
    "plain": "test",
    "hexplain": "74657374",
    "algorithm": "MD5X5PLAIN"
  }
}

It is much easier to see what is going on when you can see the nested structure of the JSON object you are trying to target data inside of:

Working Example #1 — Tested with Python 2.6.9 and 2.7.10 and 3.3.5 and 3.5.0

import json

json_string = '''
{
    "REQUEST": "FOUND",
    "739c5b1cd5681e668f689aa66bcc254c": {
        "plain": "test",
        "hexplain": "74657374",
        "algorithm": "MD5X5PLAIN"
    }
}
'''

if 'plain' in json_string:
    parsed_json = json.loads(json_string)
    print(parsed_json['739c5b1cd5681e668f689aa66bcc254c']['plain'])

'plain' is a child of '739c5b1cd5681e668f689aa66bcc254c'


Edit

The following example loops through parsed_json and checks each key for a length of 32 characters and checks the that the key has a child value of 'plain' inside it.

Working Example #2 — Tested with Python 2.6.9 and 2.7.10 and 3.3.5 and 3.5.0

import json
import re

def is_MD5(s):
    return True if re.match(r"([a-f\d]{32})", key) else False

strr = '''
{
    "REQUEST": "FOUND",
    "739c5b1cd5681e668f689aa66bcc254c": {
        "plain": "test",
        "hexplain": "74657374",
        "algorithm": "MD5X5PLAIN"
    }
}
'''

parsed_json = json.loads(strr)

for key, value in parsed_json.items():
    if is_MD5(key) and 'plain' in parsed_json[key]:
        xHash = key
        xPlain = parsed_json[key]['plain']

        print('value in key "plain" in key "{0}" is "{1}"'.format(*[xHash,
                                                                    xPlain]))

Output

the value of key "plain" in key "739c5b1cd5681e668f689aa66bcc254c" is "test"

In your data, 'plain' is not a member of parsed_json . It is a member of parsed_json['739c5b1cd5681e668f689aa66bcc254c'] . So parsed_json['739c5b1cd5681e668f689aa66bcc254c']['plain'] should work.

JSON is a hierarchical data structure. The top-level brackets indicate that the whole thing is one object that will get assigned to parsed_json . Each member is a name-value pair; the value of 'REQUEST' is 'FOUND' . The value of '739c5b1cd5681e668f689aa66bcc254c' , however, is a sub-object, indicated by the opening bracket. Its members are 'plain' , 'hexplain' , and 'algorithm' . This should be more clear if I write it like this:

parsed_json: {
    "REQUEST":"FOUND",
    "739c5b1cd5681e668f689aa66bcc254c": {
        "plain":"test",
        "hexplain":"74657374",
        "algorithm":"MD5X5PLAIN"
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM