0

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
2
  • 1
    Do you mean something other than import json / dct = json.loads( result )? Python has a built-in json module. Commented Aug 9, 2022 at 3:23
  • 1
    Have a read of this: w3schools.com/python/python_json.asp Note: This was the first google result from the search: python string to json. Commented Aug 9, 2022 at 3:25

2 Answers 2

1

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

2 Comments

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'
Have you assigned a variable named "json"?
0

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
answered Aug 9, 2022 at 3:30

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.