kingcope kingcope - 6 months ago 14
JSON Question

How to parse json text data with python

I need to make a request to the api of my client, and the api returns this data:

[6,0,'VT3zrYA',5,'USUeZWA',5,0,0,0,0,0,4,0,0,0,2,0,0,3,0,0,0,0,2,0,1,["portale.titolari.client.config.ShoulderDTO/4121330600","java.util.HashSet/3273092938","MATTEO SBRAGIA","java.util.ArrayList/4159755760","java.util.Date/3385151746","MATTEO"],0,7]


How can I parse this data and extract the following fields :

MATTEO SBRAGIA
MATTEO


I've tried this code, but it's not working :

data = json.load(output_data)
pprint data

Answer

This in fact is not a valid JSON string because it contains single quotes '. You can replace all single quotes with double quotes and then parse the string but it's a question whether this was intentional or a mistake:

import json

s = '[6,0,\'VT3zrYA\',5,\'USUeZWA\',5,0,0,0,0,0,4,0,0,0,2,0,0,3,0,0,0,0,2,0,1,["portale.titolari.client.config.ShoulderDTO/4121330600","java.util.HashSet/3273092938","MATTEO SBRAGIA","java.util.ArrayList/4159755760","java.util.Date/3385151746","MATTEO"],0,7]'

data = json.loads(s.replace("\'", '"'))

print(data[26][2])
print(data[26][5])

prints:

$ python test.py 
MATTEO SBRAGIA
MATTEO
Comments