Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python's json: AttributeError: 'str' object has no attribute 'keys'

I am trying to load a string (the actual program read this line from a file and it is a very large file that I can not manually modify) formatted as a dictionary.

I need to convert the string line into a json object so I can check value of specific key, e.g. myJson[Date] .

This is the script:

import json

mystring = "{'Date': 'Fri, 19 Apr 2019 03:58:04 GMT', 'Server': 'Apache/2.4.39', 'Accept-Ranges': 'bytes'}"


mystring = json.dumps(mystring)
myJson = json.loads(mystring)

print(str(myJson.keys()))
print(str(myJson))

I am getting this error:

AttributeError: 'str' object has no attribute 'keys'

I suspect that the mystring format is not conforming and that the single quotes should be double quotes? Given that I have a large data, and I can not simply replace single colons with double one using simple search/replace as single colons may be included in the values which I should not modify. If this is the cause of the problem, is there any way to replace the colons of the key/value pair only without touching the colons in the values? I am hoping that this is not the problem.

like image 700
user9371654 Avatar asked May 14 '19 00:05

user9371654


2 Answers

Rather than dealing with the single quoted string and struggling to convert it into json, just use ast package to convert it into a valid dict.

import ast

mystring = "{'Date': 'Fri, 19 Apr 2019 03:58:04 GMT', 'Server': 'Apache/2.4.39', 'Accept-Ranges': 'bytes'}"

my_dict = ast.literal_eval(mystring)

the result is:

> print(my_dict["Date"])
Fri, 19 Apr 2019 03:58:04 GMT

like image 90
razdi Avatar answered Nov 18 '22 02:11

razdi


This code stores the string as a dictionary in a variable called "Tempvar" From that variable you can just use the keys like a regular dictionary.

import json

mystring = "{'Date': 'Fri, 19 Apr 2019 03:58:04 GMT', 'Server': 'Apache/2.4.39', 'Accept-Ranges': 'bytes'}"

exec("tempvar = " + mystring)
mystring = json.dumps(mystring)
myJson = json.loads(mystring)

print(str(tempvar['Date']))
print(str(myJson))

Hope this helps

like image 1
I don't exist Avatar answered Nov 18 '22 01:11

I don't exist