通过API,我收到json输出,而不是将所有输出写入分析中,我只希望数据具有“ true”值。
原始json数据示例:
with open('C:\\output.json', 'w') as outfile:
for item in data["scans"]:
if 'item["detected"] === true
json.dump(data)
Python代码
scans:
Scanner2:
detected: true
version: "2.2.2.2"
result: "trojan"
update: "23142551"
所需的输出
import requests
url = '<url>'
params = {'apikey': <key>, 'resource': '<value>'}
response = requests.get(url, params=params)
result = []
with open('C:\\output.json', 'w') as outfile:
data = response.json()
for i in data['scans']:
if (i['detected']=='true'): // error thrown here
result.append(i) // TypeError: string indices must be integers
print(result)
这绝不可行,我也不知道JSON,但我必须证明我尝试了大声笑。
谢谢!
更新
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/6.26.0/polyfill.min.js"></script>
<script type="text/babel" data-presets="es2015,stage-2">
const res = await axios.get('https://api.hnpwa.com/v0/news/1.json')
console.log(res)
</script>
答案 0 :(得分:1)
result =[]
with open('C:\\output.json', 'w') as outfile:
data = json.load(outfile)
for i in data['scans']:
if i['detected']=='true':
result.append(i)
print(result)
答案 1 :(得分:1)
您的原始数据json看起来不像json(查找json的样子)。但是假设它被错误地复制,下面的字典理解将适用于json:
data = response.json()
with open('C:\\output.json', 'w') as outfile:
result = {k: v for k, v in data['scans'].items() if v['detected']}
outfile.write(json.dumps(result))