I've been working on a side-project and I've been struggling with extracting data from a JSON response using Python. Whatever I come up with, I can't seem to have a proper formatted JSON result (probably because I'm new to Python, so I could use some guidance)
With these few lines I query an API and write the response to a file:
response = client.get_products()
with open('file.json', 'w') as f:
f.write(str(response))
The generated json file reads as follows:
Output
{
'version': 'value',
'list': [
'{
"product":
{
"attributes":
{
"name":"value",
"location":"value"
},
"description":"text productA"
},
"version":"value"
}',
'{
"product":
{
"attributes":
{
"name":"value",
"location":"value"
},
"description":"text productB"
},
"version":"value"
}'
],
'date':'value'
}
That does not look like valid JSON, notice the single quotes... but, all within {"product":...} looks fine. So i tried another approach:
response = client.get_products()
with open('file.json', 'w') as output:
json.dump(response, output)
This time the json file contains the following:
Output
{
"version": "value",
"list": [
"{
\"product\":
{
\"attributes\":
{
\"name\":\"value\",
\"location\":\"value\"
},
\"description\":\"text productA\"
},
\"version\":\"value\"
}",
"{
\"product\":
{
\"attributes\":
{
\"instanceType\":\"value\",
\"location\":\"value\"
},
\"description\":\"text productB\"
},
\"version\":\"value\"
}"
],
"date": "value"
}
Hmmm, not what I had in mind either...
Question: What am I doing wrong? and more important, how can I write the response to a valid formatted JSON file? So expected outcome should be:
Expected output
{
"version": "value",
"list": [
{
"product":
{
"attributes":
{
"name":"value",
"location":"value"
},
"description":"text productA"
},
"version":"value"
},
{
"product":
{
"attributes":
{
"name":"value",
"location":"value"
},
"description":"text productB"
},
"version":"value"
}
],
"date": "value"
}
In the end I which to isolate all "product" entries in the response, bonus points for additional tips on how to achieve this :)
responsean actual python dict? It looks like you're working with a string since it has both single and double quotes.