i want to get token through the result of REST API and it has done and success. the result of REST API shown below following print(result) of python
'{"UserId":"202","UserName":"xxx","UserMail":"yyy","Token":"abcdfghoijkalt"}'
do you know how to get "Token" as variable?, so i can get to next step. thank you
Ynjxsjmh
30.3k7 gold badges43 silver badges64 bronze badges
asked Aug 9, 2022 at 3:21
Handri Mauludin Maulana
852 silver badges14 bronze badges
2 Answers 2
You can use json.loads
import json
jObject = json.loads('{"UserId":"202","UserName":"xxx","UserMail":"yyy","Token":"abcdfghoijkalt"}')
# This should give you the value you are looking for:
token = jObject["Token"]
print(token)
answered Aug 9, 2022 at 3:37
user19707153
Sign up to request clarification or add additional context in comments.
2 Comments
Handri Mauludin Maulana
it totally works. thank you, but i have new issue with same json format as same as above, that ther error says: 'dict' object has no attribute 'loads'
I have written a short write util function (below) which I include in every project I work on. So if your target file has a .json extension, it automatically format it into json.
eg. write(result, "dst_dir/dst_file.json")
import json
def write(content, file, **kwargs):
if not isinstance(file, str):
file = str(file)
if file.endswith('.json'):
with open(file, 'w') as f:
json.dump(content, f, indent=2, **kwargs)
else:
with open(file,'w') as f:
f.write(content, **kwargs)
write(result, "dst_dir/dst_file.json") # To run it with your result
Comments
lang-py
import json/dct = json.loads( result )? Python has a built-injsonmodule.python string to json.