Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
  }
}
like image 922
Uber Avatar asked Dec 08 '25 22:12

Uber


1 Answers

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"
like image 147
jesterjunk Avatar answered Dec 10 '25 11:12

jesterjunk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!