Home > front end >  How to parse json in python
How to parse json in python

Time:08-09

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

CodePudding user response:

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)

CodePudding user response:

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
  • Related