2

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.

1
  • don't know how you expect it to say 3, that is not in your example. Commented Oct 23, 2015 at 17:59

2 Answers 2

1

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'])
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.