Extract key value from JSON using python NameError - python

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'])

Related

Getting the last value of a key value pair in a json like string

I have a json like string (incomplete json) in which I am trying to retrieve the value of the last key:value pair. The incomplete json like string looks like this:
"BaseCode":null,"BrokerSymbol":null,"CustID":null,"SynthDesc":""}],"#nexturl":"https://someurl.com"}
I am trying to access the value of the #nexturl key and this is the code I've till now:
str1.split(":")[-1]
this gives the output //someurl.com. 2 issues here are that splitting on : removes the https prefix and also doesn't seem like a great approach as if the url contains any more : it will split on that. Is there someway I can get the entire value of #nexturl key?
As requested, assuming your string is as follows:
mystr = '"BaseCode":null,"BrokerSymbol":null,"CustID":null,"SynthDesc":""}],"#nexturl":"https://someurl.com"}'
You can grab the key:value pair containing “#nexturl” by using:
mystr[mystr.index('"#nexturl":'):len(mystr)-1]

Reading JSON file using json.load

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.

Getting the value of a key in a dict

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.

Parse JSON in python to a dictionary

A bit lost after much research. My code below parses the JSON to a dictionary I have thought using json load
response = json.load(MSW) # -->Will take a JSON String & Turn it into a python dict
Using the iteration below I return a series like this which is fine
{u'swell': {u'components': {u'primary': {u'direction': 222.5}}}}
{u'swell': {u'components': {u'primary': {u'direction': 221.94}}}}
ourResult = response
for rs in ourResult:
print rs
But how oh how do I access the 222.5 value. The above appears to just be one long string eg response[1] and not a dictionary structure at all.
In short all I need is the numerical value (which I assume is a part of that sting) so I can test conditions in the rest of my code. Is is a dictionary? With thanks as new and lost
You have to use python syntax as follows:
>>> print response['swell']['components']['primary']['direction']
222.5
Just access the nested dictionaries, unwrapping each layer with an additional key:
for rs in ourResult:
print rs['components']['primary']['direction']

How To Format a JSON Text In Python?

When I call the JSON file for Vincent van Gogh's List of Works wikipedia page, using this url,
it obviously returns a huge blob of text which I believe is some sort of dictionary of lists.
Now, someone has already shown me Python's import wikipedia feature, so skip that. How can I decode this JSON? I feel like I have tried everything in Python 3's library, and always get an error, like I get if I try this code for example:
data = urllib.request.urlopen(long_json_url)
stuff = json.load(data) #or json.loads(data)
print(stuff)
it returns
TypeError: the JSON object must be str, not 'bytes'
Or if I try this code:
data = urllib.request.urlopen(longurl)
json_string = data.read().decode('utf-8')
json_data = json.loads(json_string)
print(json_data)
It doesn't return an error, but just what looks like nothing
>>>
>>>
But if I highlight that empty space and paste it, it pastes the same blob of text.
{'warnings': {'main': {'*': "Unrecognized parameter: 'Page'"}}, 'query': {'normalized': [{'from': 'list of works by Vincent van Gogh',... etc
If I try a for loop:
for entry in json_data:
print(entry)
It returns
>>>
query
warnings
>>>
And that's it. So it's not returning an error there, but not really much else, just two values? How would you make the JSON data into a workable Python dict or list? Or at the very least, into a more vertical format that I could actually read?
How would you make the JSON data into a workable Python dict or list?
You're already doing that with
json_data = json.loads(json_string)
This however:
for entry in json_data:
print(entry)
will only print the keys of your dictionaries. If you want to print the values, you need to use:
for entry in json_data:
print(json_data[entry])
if you inspect the data, you'll see that there are two keys for the main dictionary. The ones you already got by iterating over the dict:
{u'query': {...}, u'warnings': {...}}

Categories