I'm trying to filter a data that is in json format but after it did the json.dumps it's still not in dict format and when I try to filter it, doesn't work.
This is my code:
import json
import urllib3
http = urllib3.PoolManager()
user = ''
def data_json():
url = '' user
r = http.request(
'GET',
url,
)
data = json.loads(r.data.decode('utf-8'))
data2 = json.dumps(dados, indent=4, sort_keys=True, separators=(',', ':'))
print (data2)
This is the output that it returns:
{
"result":"Data: {\"prescription":\"Nimesulida \",\"data\":\"14/10\"}"
}
And I would like to filter just the 'data' result from this output, I've tried this two ways:
print(data2[1]['data'])
print(data2['result']['data'])
but it returns this error message: string indices must be integers. Does anyone know how can I filter this data?
CodePudding user response:
You've got a bit of a mess. While the JSON is valid, it is oddly formed. Below I've reverse-engineered the original data
value since it wasn't provided directly:
import json
import ast
data2 = r'''{
"result":"Data: {\"prescription\":\"Nimesulida \",\"data\":\"14/10\"}"
}'''
print(data2) # Matches your claim,^-except there was a missing backslash here
data = json.loads(data2) # Get original data back
print(data)
result = data['result'] # access result, value is a *string*
d = ast.literal_eval(result[6:]) # slice off 'Data: ' and convert to dict
print(d['data'])
Output:
14/10