简体   繁体   English

如何使用python提取JSON中的特定多个值?

[英]How to extract specific multiple values in JSON using python?

I Have to extract specific multiple values and print those specific values in a file if possible. 我必须提取特定的多个值,并在可能的情况下将这些特定的值打印在文件中。

I tried the below code to do this 我尝试下面的代码来做到这一点

JSON value from URL is: 
{'data': [{'value': '0.0.0.0'}, {'value': '0.0.0.1'}, {'value': '0.0.0.2'}]}

import requests
import json
url = 'https://www.example.com'
response = requests.get('url', headers=headers , verify=False)  
json_data = json.loads(response.text)
value = json_data['data'][0]['value']
print (value)

output of this : 0.0.0.0

But i want to print in a file(.txt) all these values like below: 但是我想在文件(.txt)中打印所有这些值,如下所示:

0.0.0.0
0.0.0.1
0.0.0.3

Please help me on this. 请帮我。

What you want is a loop 你想要的是一个循环

json_data = {'data': [{'value': '0.0.0.0'}, {'value': '0.0.0.1'}, {'value': '0.0.0.2'}]}

for x in json_data['data']:
  print (x['value'])

To write the values to a file, expand @ergonaut's answer as here: 要将值写入文件,请按如下所示扩展@ergonaut的答案:

json_data = {'data': [{'value': '0.0.0.0'}, {'value': '0.0.0.1'}, {'value': '0.0.0.2'}]}
with open("test.txt", "w") as f:
    for x in json_data['data']:
        f.write(x['value'] + '\n')

Test the entries in test.txt : 测试test.txt的条目:

with open("test.txt", "r") as f:
    data = f.readlines()
for line in data:
    print line.rstrip('\n')

Output: 0.0.0.0 0.0.0.1 0.0.0.2 输出: 0.0.0.0 0.0.0.1 0.0.0.2

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

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