How do I convert this list to a valid json object in Python 3.7?
Question:
I have the following list that I need to convert into a valid JSON object:
data = ['{"id":"0","jsonrpc":"2.0","method":"RoutingRequest","params":{"barcode":"5694501","itemID":113},"timestamp":"2018-08-06T15:38:40.531"}', '']
I’ve tried:
import json
my_json = data.decode('utf8').replace("'", '"')
my_json = json.loads(my_json)
Keep getting this error: raise TypeError(f’the JSON object must
be str, bytes or bytearray, ‘ TypeError: the JSON object must be str,
bytes or bytearray, not list
What am I doing wrong? (btw, I’m new to Python)
Answers:
You have a list of data. Iterate over it and then use json.load
Ex:
import json
data = ['{"id":"0","jsonrpc":"2.0","method":"RoutingRequest","params":{"barcode":"5694501","itemID":113},"timestamp":"2018-08-06T15:38:40.531"}', '']
data = [json.loads(i) for i in data if i] #Iterate your list check if you have data then use json.loads
print(data)
Output:
[{u'params': {u'itemID': 113, u'barcode': u'5694501'}, u'jsonrpc': u'2.0', u'id': u'0', u'timestamp': u'2018-08-06T15:38:40.531', u'method': u'RoutingRequest'}]
I have the following list that I need to convert into a valid JSON object:
data = ['{"id":"0","jsonrpc":"2.0","method":"RoutingRequest","params":{"barcode":"5694501","itemID":113},"timestamp":"2018-08-06T15:38:40.531"}', '']
I’ve tried:
import json
my_json = data.decode('utf8').replace("'", '"')
my_json = json.loads(my_json)
Keep getting this error: raise TypeError(f’the JSON object must
be str, bytes or bytearray, ‘ TypeError: the JSON object must be str,
bytes or bytearray, not list
What am I doing wrong? (btw, I’m new to Python)
You have a list of data. Iterate over it and then use json.load
Ex:
import json
data = ['{"id":"0","jsonrpc":"2.0","method":"RoutingRequest","params":{"barcode":"5694501","itemID":113},"timestamp":"2018-08-06T15:38:40.531"}', '']
data = [json.loads(i) for i in data if i] #Iterate your list check if you have data then use json.loads
print(data)
Output:
[{u'params': {u'itemID': 113, u'barcode': u'5694501'}, u'jsonrpc': u'2.0', u'id': u'0', u'timestamp': u'2018-08-06T15:38:40.531', u'method': u'RoutingRequest'}]