首页 > 解决方案 > 在python3中操作类型字节

问题描述

你能帮我从这个字节中获取报告的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
}'

标签: python-3.x

解决方案


您还没有清楚地提到所有可能的输入。但是,对于给定的输入,下面的程序将起作用!这有点硬编码!

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!']

推荐阅读