1

I need to get data from this API https://api.storj.io/contacts/f52624d8ef76df81c40853c22f93735581071434 (sample node)

This is my code (python):

import requests
f = requests.get('https://api.storj.io/contacts/f52624d8ef76df81c40853c22f93735581071434')
print f.text

I want to save only protocol, responseTime and reputation in three subsequent lines of the txt file. It's supposed to look something like this::

protocol: 1.2.0
responseTime: 8157.912472694088
reputation: 1377

Unfortunately, I'm stuck at this point and I can not process this data in any way

3 Answers 3

2
import requests
f = requests.get('https://api.storj.io/contacts/f52624d8ef76df81c40853c22f93735581071434')

# Store content as json
answer = f.json()

# List of element you want to keep
items = ['protocol', 'responseTime', 'reputation']

# Display
for item in items:
    print(item + ':' + str(answer[item]))

# If you want to save in a file
with open("Output.txt", "w") as text_file:
    for item in items:
        print(item + ':' + str(answer[item]), file=text_file)

Hope it helps! Cheers

Sign up to request clarification or add additional context in comments.

Comments

1

You just need to transform to a JSON object to be able to access the keys

import requests
import simplejson as json

f = requests.get('https://api.storj.io/contacts/f52624d8ef76df81c40853c22f93735581071434')

x = json.loads(f.text)

print 'protocol: {}'.format(x.get('protocol'))
print 'responseTime: {}'.format(x.get('responseTime'))
print 'reputation: {}'.format(x.get('reputation'))

Comments

1

This is a very unrefined way to do what you want that you could build off of. You'd need to sub in a path/filename for text.txt.

import requests
import json

f = requests.get('https://api.storj.io/contacts/f52624d8ef76df81c40853c22f93735581071434')
t = json.loads(f.text)

with open('text.txt', 'a') as mfile:
  mfile.write("protocol: {0}".format(str(t['protocol'])))
  mfile.write("responseTime: {0}".format(str(t['responseTime'])))
  mfile.write("reputation: {0}".format(str(t['reputation'])))

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.