I try to get the value of a key in a dict by :
print User['LocationName']
This is giving me a TypeError: string indices must be integers, not str error.
This is the dict
{u'LocationName': u'home', u'First Name': u'Bob',...... }
I'm not sure what this error means
User is not a dict. User is a string. Figure out why it's a string, and change that.
The error means that you are trying to access a "part" of your string as if it was a list. But you are not using a integer as parameter to access a list, you are using a string.
Try to use:
eval(User)
then you can:
print User['LocationName']
This usually happens when you save a JSON into a file, using python. It's like Python saved your dict as a dict Object, but when you read from the file, the object is read by string. So, when you call eval(), you get a dict again.
Related
I am creating a python script to extract values, Name from the JSON Key Details from the JSON result. Python error mentioned KeyError 'details[name]'. The JSON example is found below. The JSON is incomplete. JSON has other data which I am not going to put it here as it is confidential.
details: {'id': 5555, 'name': 'Timothy', 'Gender': 'Male'}
My Python script is shown below
print(json_data['details[name]'])
Error Message
print(json_data['details[name]'])
KeyError: 'details[name]'
I want to print the result
Timothy
What am I missing?
Assuming json_data is the name you've chosen for the entirety of the JSON object, you need provide a proper index for json_data in your print statement. Your current index is a string because you've captured your brackets inside of the apostrophes. The way you're indexing the JSON object is also incorrect.
JSON objects are essentially multidimensional dictionaries. The way you print the value of a value of a key is like this: print(dict["key"]["value"]).
Assuming the details key is also a string, the correct way to print the value of name from the key "details" is: print(json_data["details"]["name"]
do it one key at a time rather than trying to fit both the keys into one set of quotes as you originally had.
print(json_data['details']['name'])
I have a data.json file, which looks like this:
["{\"Day\":\"Today\",\"Event\":\"1\", \"Date\":\"2019-03-20\"}"]
I am trying to get "Event" from this file using python and miserably failing at this.
with open('data.json', 'r') as json_file:
data = json.load(json_file)
print (data['Event'])
I get the following error:
TypeError: list indices must be integers or slices, not str
And even when I try
print (data[0]['Event'])
then I get this error:
TypeError: string indices must be integers
One more thing:
print(type(data))
gives me "list"
I have searched all over and have not found a solution to this. I would really appreciate your suggestions.
You could use the ast module for this:
import ast
mydata = ["{\"Day\":\"Today\",\"Event\":\"1\", \"Date\":\"2019-03-20\"}"]
data = ast.literal_eval(mydata[0])
data
{'Day': 'Today', 'Event': '1', 'Date': '2019-03-20'}
data['Event']
'1'
Edit
Your original code does load the data into a list structure, but only contains a single string entry inside that list, despite proper json syntax. ast, like json, will parse that string entry into a python data structure, dict.
As it sits, when you try to index that list, it's not the same as calling a key in a dict, hence the slices cannot be str:
alist = [{'a':1, 'b':2, 'c':3}]
alist['a']
TypeError
# need to grab the dict entry from the list
adict = alist[0]
adict['a']
1
You need to convert the elements in data to dict using json module.
Ex:
import json
with open(filename) as infile:
data = json.load(infile)
for d in data:
print(json.loads(d)['Event'])
Or:
data = list(map(json.loads, data))
print(data[0]["Event"])
Output:
1
Your problem is that you are parsing it as a list that consists of a single element that is a string.
["{\"Day\":\"Today\",\"Event\":\"1\", \"Date\":\"2019-03-20\"}"]
See how the entire content of the list is surrounded by " on either side and every other " is preceded by a \? The slash generally means to ignore the special meaning the following character might have, but interpret it as purely a string.
If you have control over the file's contents, the easiest solution would be to adjust it. You will want it to be in a format like this:
[{"Day":"Today", "Event": "1", "Date": "2019-03-20"}]
Edit: As others have suggested, you can also parse it in its current state. Granted, cleaning the data is tedious, but oftentimes worth the effort. Though this may not be one of those cases. I'm leaving this answer up anyway because it may help with explaining why OPs initial attempt did not work, and why he received the error messages he got.
I have a simple file (username.json) as shown below:
{"lastname": "doe", "firstname": "john"}
I use the following code to read the file:
with open(filename) as file_obj:
dictionary = json.load(file_obj)
print(dictionary['firstname'])
But when I print the dictionary value for the key "firstname" it prints nothing.
When I print the dictionary I get the following:
{u'lastname': u'doe', u'firstname': u'john'}
I know that "u" stands for unicode but for some reason I am not able to use the firstname and lastname keys.
UPDATE:
For some reason it works now!
json.loads converts a json object to the python equivalent.
This means it uses lists and dicts instead of arrays and objects. You are seeing the representation of the former.
doctionary["firstname"] will get you the value in first name (ie, "doe") while it's still a python object.
If you want to see json again, you'll need to pass it through json.dumps - but of course you won't be able to manipulate it as above when in that format.
{
"card_quota": 0,
"custom_data": "{\"child_name\":\"홍설\",\"uid\":\"29\",\"lid\":\"56\",\"count\":\"1\",\"schedule\":\"2016-06-18(토)\"}",
"escrow": false
}
This is dictionary type of python. I konw to get value using a code like temp['card_quata']. But i want to know using key in ['custom_data'] getting value like child_name or uid .. How can i do that?
You can parse custom_data with json.loads and then access the returned dict:
>>> import json
>>> json.loads(temp['custom_data'])['child_name']
'홍설'
Note that the example data you provided is not valid Python since Python uses False instead of false.
You can simply get the values of any dictionary using the keys. So lets take it step by step:
first, lets get the dictionary -
temp['custom_data']
will give you the child dictionary, then, in order to access the items of this child dict, you can use the child keys:
temp['custom_data']['child_name']
temp['custom_data']['uid']
etc.
I have a program that has a save file full of lists. It Loads up the Items by making lists. It gets the Names from the file too. Since I couldn't "unstring" a string so I put the names as keys. My problem is re-saving the lists when you are done using the program. I cant seem to access the contents inside the list to write them to a file. I have another List with keys so I can access the Names.
ListKey = {1:'Food', 2:'Veggie'}
List={'Food':['apple','pear','grape'], 'Veggies':['carrot','Spinach','Potato']}
file.write(ListKey[1]) #works fine
currentList=ListKey[1]
file.write(List[currentList[1]]) #Doesn't Work
When I try to do the code above, I get a Key Error, I know it is trying to write the 'o' in food. Is there anyway to get around this?
It looks like you are trying to access a value inside your key pairs. Try:
List[currentList][0] to access 'apple'
List[currentList][1] to access 'pear'
etc...
alternatively if you want all the values, it would look like
List[currentList] or
List['Food']
Hope this helps, just your syntax of how to access the list inside.
edit:
https://docs.python.org/2/tutorial/datastructures.html#nested-list-comprehensions
(added link to data structure docs)
currentList[1] is just the value o, use:
file.write(List[currentList])
ListKey = {1:'Food', 2:'Veggie'}
List={'Food':['apple','pear','grape'], 'Veggies': ['carrot','Spinach','Potato']}
currentList = ListKey[1] #'Food'
currentList[1] # 'o'
You are actually indexing into the string "Food". Hence currentList[1] is 'o'. Since List has no key 'o' you get at key error.