使用python创建嵌套的json

时间:2015-06-25 12:45:18

标签: python json nested

  

{" 0":{" posted_date":" 2015年6月25日"}," 1":{" posted_date& #34;:" 2015年6月26日"}}

注意:

  1. 那' 0'和' 1'变量 - ' count',变量通过repeat / loop
  2. 生成
  3. " posted_date"是一个字符串
  4. " 2015年6月25日"和" 2015年6月26日"也是可变的 - ' date'
  5. 如何使用python创建类似上面的JSON输出?

    [编辑 - 不工作代码]

    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))
    

2 个答案:

答案 0 :(得分:0)

首先按照您希望的方式创建地图:

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

然后使用json.dumps()获取json

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

答案 1 :(得分:0)

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)

您不需要使用&#34;计数&#34;变量