在python3中操作类型字节

时间:2019-12-13 11:02:13

标签: python-3.x

能否请您帮我从此字节中获取报告的ID?

b'{
"message":"The report with id 9520 was created but it is invalid!", 
"violations":"{\\"schemaLocation\\":\\"#\\",\\"pointerToViolation\\":\\"#\\",\\"causingExceptions\\":[{\\"schemaLocation\\":\\"#\\",\\"pointerToViolation\\":\\"#\\",\\"causingExceptions\\":[],\\"keyword\\":\\"required\\",\\"message\\":\\"required key [reportType] not found\\"},{\\"schemaLocation\\":\\"#\\",\\"pointerToViolation\\":\\"#\\",\\"causingExceptions\\":[],\\"keyword\\":\\"required\\",\\"message\\":\\"required key [finishedAt] not found\\"},{\\"schemaLocation\\":\\"#/properties/hosts/items\\",\\"pointerToViolation\\":\\"#/hosts/0\\",\\"causingExceptions\\":[],\\"keyword\\":\\"required\\",\\"message\\":\\"required key [applications] not found\\"}],\\"message\\":\\"3 schema violations found\\"}",    
"valid":false
}'

1 个答案:

答案 0 :(得分:0)

您尚未清楚提及所有可能的输入。但是,对于给定的输入,以下程序将起作用!这有点硬编码!

import json

data=b'{"message":"The report with id 9520 was created but it is invalid!", "violations":"{\\"schemaLocation\\":\\"#\\",\\"pointerToViolation\\":\\"#\\",\\"causingExceptions\\":[{\\"schemaLocation\\":\\"#\\",\\"pointerToViolation\\":\\"#\\",\\"causingExceptions\\":[],\\"keyword\\":\\"required\\",\\"message\\":\\"required key [reportType] not found\\"},{\\"schemaLocation\\":\\"#\\",\\"pointerToViolation\\":\\"#\\",\\"causingExceptions\\":[],\\"keyword\\":\\"required\\",\\"message\\":\\"required key [finishedAt] not found\\"},{\\"schemaLocation\\":\\"#/properties/hosts/items\\",\\"pointerToViolation\\":\\"#/hosts/0\\",\\"causingExceptions\\":[],\\"keyword\\":\\"required\\",\\"message\\":\\"required key [applications] not found\\"}],\\"message\\":\\"3 schema violations found\\"}","valid":false}'


data = json.loads(data)["message"].split()

data是一个包含message键值的列表!您可以索引它以获得所需的值!

>>> data
['The', 'report', 'with', 'id', '9520', 'was', 'created', 'but', 'it', 'is', 'invalid!']