Reputation:
I'm currently learning the basics behind Python. I've been tasked with creating a few simple database-related Python scripts. I'm having an issue working with JSON on my SELECT
script.
The data format I need is as follows;
{
"Data": {
"name1": "val1",
"name2": "val2",
"name3": "val3",
"name4": "val4"
},
"IMPORTANT_NOTE": "This data is from the test database - used for demonstration only!"
}
The data itself is stored as JSON within the DB so it's 1 field. The data is retrieves as follows;
try:
db = MySQLdb.connect(dbhost, dbuser, dbpass, sqldb)
except:
msg = "Connect error"
else:
cursor = db.cursor()
sql = "SELECT JSON_DATA FROM TEST_DB_TABLE WHERE DATA_GUID= %s"
args = "TestData"
cursor.execute(sql,args)
for row in curosr.fetchall() : jsondata = row[0]
finally:
db.close()
This returns the following if i print(jsondata)
;
{
"name1": "val1",
"name2": "val2",
"name3": "val3",
"name4": "val4"
}
I'm used to PHP so I'd expect to use an array to form the rest of the data and finalize it with json_encode
. I understand that Python's equivalents to arrays are dictionaries so I feel like that's what I should use here. I did try this at the end;
data = json.loads(jsondata)
FinOut = {"Data": data, "IMPORTANT_NOTE": "This data is from the test database - used for demonstration only!"
print(FinOut)
... The issue here is that it returns invalid JSON;
{'Data': {u'name1': u'val1', u'name2': u'val2', u'name3': u'val3', u'name4': u'val4'}, 'IMPORTANT_NOTE': 'This data is from the test database - used for demonstration only!'}
I did try json.load(jsondata)
instead but then cgitb
reports an error (I assume because .load
is a file-based equivalent;
<type 'exceptions.AttributeError'>: 'str' object has no attribute 'read'
args = ("'str' object has no attribute 'read'",)
message = "'str' object has no attribute 'read'"
Any ideas on how I correct this to output the data in a format similar to the one at the top?
Upvotes: 0
Views: 1126
Reputation: 599490
You converted your JSON object to a Python dict. Why are you expecting a dict to be valid JSON? It's not. If you want JSON, you should convert your dict back into that format:
json_data = json.dumps(FinOut)
Upvotes: 2