简体   繁体   中英

How do I format a list of numbers for JSON API payload?

I need to post some JSON to a REST API. I want the payload to look like this:

{"id": {2342,2354,5676,7423}}

The numbers need to come from a list:

userid = [2342,2354,5676,7423]

I tried to loop through the list using something like this:

payload = {"id": {",".join([str(i) for i in userid])}}

But that gives me a quote around all the numbers which then fails:

{'id': {'2342,2354,5676,7423'}}

How can I insert those numbers into JSON without the quotes?

Thanks!

It is impossible. {"id": {2342,2354,5676,7423}} is not a valid JSON format. You can verify the validity of a JSON object using the function json.dumps from the json package.

here's how :

payload = {2342,2354,5676,7423}
x = {"id": payload}

to have this:

{"id": {2342,2354,5676,7423}}

but this is not a valid JSON format

do you mean

payload = {"id": row} 

to have something like this

{'id': [2342, 2354, 5676, 7423]}

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