简体   繁体   中英

How to parse json in python

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

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM