简体   繁体   English

如何在Python 3.7中将此列表转换为有效的json对象?

[英]How do I convert this list to a valid json object in Python 3.7?

I have the following list that I need to convert into a valid JSON object: 我有以下列表需要转换为有效的JSON对象:

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 不断收到此错误:引发TypeError(f'JSON对象必须为str,字节或字节数组,'TypeError:JSON对象必须为str,字节或字节数组,而不是列表

What am I doing wrong? 我究竟做错了什么? (btw, I'm new to Python) (顺便说一句,我是Python的新手)

You have a list of data. 您有一个数据列表。 Iterate over it and then use json.load 对其进行迭代,然后使用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'}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM