Python Json.load Returning String Instead Of Dictionary
Solution 1:
In your json stub "data"
key contains list. In your code you refer to it as a dictionary: i.get('data').get('BaselineExposure')
Instead you should iterate through your "data"
.
For example:
data = i.get('data')
for d indata:
print(d.get('BaselineExposure'))
So basically be careful with nested items.
Also why do you use i.get('id').get('value')
. Instead i.get('id')
should be enough and additional .get('value')
should raise AttributeError
, isn't it?
Solution 2:
Overview: I assume the json is stored as a dictionary. I convert the dictionary to a json string using json.dumps. I pip install json2xml json2xml to convert the json string so it can be converted to xml. I then load the xml into a dom tree for searching. I search for the node in the xml tree using getElementsByTagName and display the value. My approach is more programmer friendly.
from json2xml import json2xml
from json2xml.utils import readfromurl, readfromstring, readfromjson
from xml.dom.minidom import parse, parseString
dict={
"id": "Canon EOS 100D",
"data": [{
"SourceFile": "./Canon 100D/canon_eos_100d_11.dng",
"ExifToolVersion": 10.07,
"Directory": "./Canon 100D",
"FileSize": "18 MB",
"FileModifyDate": "2016:05:02 23:03:14-07:00",
"FileAccessDate": "2016:05:03 01:45:03-07:00",
"FileInodeChangeDate": "2016:05:02 23:03:14-07:00",
"FilePermissions": "rw-r--r--",
"ColorMatrix2": "0.6602 -0.0841 -0.0939 -0.4472 1.2458 0.2247 -0.0975 0.2039 0.6148",
"CameraCalibration1": "1.0648 0 0 0 1 0 0 0 0.9881",
"CameraCalibration2": "1.0648 0 0 0 1 0 0 0 0.9881",
"AnalogBalance": "1 1 1",
"AsShotNeutral": "0.512769 1 0.584809",
"BaselineExposure": -0.25,
"RedBalance": 1.950195
}]
}
#convert dictionary to a string
json_data=json.dumps(dict,indent=4)
data=readfromstring(json_data)
xml=json2xml.Json2xml(data).to_xml()
dom=parseString(xml)
element=dom.getElementsByTagName('BaselineExposure')
print(element[0].firstChild.nodeValue)
Post a Comment for "Python Json.load Returning String Instead Of Dictionary"