简体   繁体   中英

Use python to create a nested json

{"0":{"posted_date":"25 Jun 2015"},"1":{"posted_date":"26 Jun 2015"}}

Note:

  1. that '0' and '1' are variable - 'count', the variable is generate through repeat/loop
  2. "posted_date" is a string
  3. "25 jun 2015" and "26 jun 2015" are also variable - 'date'

How to create a JSON output like above with python?

[edit-not working code]

import json
final = []
count = 0
postID = 224 
while postID < 1200:
    final.append({count: {"posted_ID":postID}})
    count = count + 1
    postID = postID * 2
print str(json.dumps(final))

First create the map the way you want it:

outMap = {}
outMap["0"]={}
outMap["0"]["posted_date"]="25 Jun 2015"
outMap["1"]={}
outMap["1"]["posted_date"]="26 Jun 2015"

Then use json.dumps() to get the json

import json
outjson = json.dumps(outMap)
print(outjson)
import json

dates = ["25 Jun 2015", "26 Jun 2015", "27 Jun 2015"]

result = {}
for each, date in enumerate(dates):
    result.update({each: {"posted_data": date}})

jsoned = json.dumps(result)

You don't need to use the "count" variable

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