How to filter out data from a print out message

Question:

I have this one problem, where I print out a message response from a website(JSON response), and the response I get is this.

Here is my model with fake data:

{"token": "MTAxOTAwNjM4NjEyMzg0OTkwMQ.8hkyLV.n0ir2UA4qFE5pXen9YnPtFzgn4xP8tHmVmmkrl", "user_settings": {"locale": "en-US", "theme": "dark"}, "user_id": "101900638614857883"}

And, if I only want the value of "token" data which are this (MTAxOTAwNjM4NjEyMzg0OTkwMQ.8hkyLV.n0ir2UA4qFE5pXen9YnPtFzgn4xP8tHmVmmkrl) and I want to store it into a txt file, is there any good way to do it?

Thank you, guys!

I tried print(r.text('token')) but it did not work, since it only works on printing the category of the data’s (like : Category : {"token" : 'daefafa', "user-id" : 'er121231231', more})

Asked By: RexGuard

||

Answers:

You need to parse the JSON into a dictionary using json.loads(). Like this:

import json

# ...
# request-getting code
# ...

data = json.loads(r.text)
print(data['token'])
Answered By: Michael M.

In python, JSON is treated as a dictionary.
To filter it use dictionary comprehension

tokenData = {key: val for key,val in data_json.items() if key == 'token'}

Full Code Snippet :

from urllib.request import urlopen
import json

url = "enter-your-url"
response = urlopen(url)

data_json = json.loads(response.read())
print(type(data_json))  # <class 'dict'>

#use dict comprehension 
jsonToken = {key: val for key,val in data_json.items() if key == 'result'}

strToken = json.dumps(jsonToken)   
# Only string json can be written to files

with open('data.txt','w') as file:
    file.write(strToken)
file.close()
Answered By: ikurious
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.