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:
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:
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
:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.