我将此字符串作为来自网址的响应的一部分:
b'{"warnings":[{"code":3,"message":"Invalid number"}],"errors":[{"code":4,"message":"No recipients specified"}],"status":"failure"}'
我一直在尝试删除b
并读入JSON解析器,但出现错误。
我的目标是读取警告和错误的代码和消息(如果存在)。
我尝试过:
import json
import requests
if "warnings" in response:
response = response[1:]
print(response)
json_data = json.loads(response)
print(json_data)
但是我得到了
---------------------------------------------------------------------------
JSONDecodeError Traceback (most recent call last)
<ipython-input-16-17ab7818300e> in <module>()
5 response = response[1:]
6 print(response)
----> 7 json_data = json.loads(response)
8 print(json_data)
/usr/lib/python3.6/json/__init__.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
352 parse_int is None and parse_float is None and
353 parse_constant is None and object_pairs_hook is None and not kw):
--> 354 return _default_decoder.decode(s)
355 if cls is None:
356 cls = JSONDecoder
/usr/lib/python3.6/json/decoder.py in decode(self, s, _w)
337
338 """
--> 339 obj, end = self.raw_decode(s, idx=_w(s, 0).end())
340 end = _w(s, end).end()
341 if end != len(s):
/usr/lib/python3.6/json/decoder.py in raw_decode(self, s, idx)
355 obj, end = self.scan_once(s, idx)
356 except StopIteration as err:
--> 357 raise JSONDecodeError("Expecting value", s, err.value) from None
358 return obj, end
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
当我尝试不切掉第一个字符时,
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
答案 0 :(得分:1)
response = response[1:]
从json字符串中删除第一个字符,从而使其无效。要删除warnings
条目,请先创建一个字典,然后将其删除:
response = b'{"warnings":[{"code":3,"message":"Invalid number"}],"errors":[{"code":4,"message":"No recipients specified"}],"status":"failure"}'
result = json.loads(response)
if "warnings" in result:
del result["warnings"]
print(result)
打印
{'errors': [{'code': 4, 'message': 'No recipients specified'}], 'status': 'failure'}
答案 1 :(得分:1)
我认为这可能对您有所帮助
decoded_response = response.decode()
data = json.loads(decoded_response)
print(data)
答案 2 :(得分:0)
我不明白您为什么要切掉第一个字符。不要那样做只需将整个字符串传递到json.loads
。
答案 3 :(得分:0)
这是一个字节对象,您可以使用以下函数将其解码为字符串。
res=response.decode('utf-8')
data = json.loads(res)
json_data = json.loads(data)
print(json_data)
希望这会有所帮助:)
答案 4 :(得分:0)
您来自网址的响应是一个字节数组。您需要先将其转换为字符串对象,然后才能通过Json模块对其进行解析。
data = json.loads(f.decode())