格式python输出到json [英] format python output to json
问题描述
{
1224:{
OUT3FA_5:12 ,
IN1:37,
Total_IN1:37
},
1225:{
OUT3FA_5:24,
IN1:59,
Total_IN1:22
}
}
但是我想做的就是这样做:
{
success:true ,
data:[
{
Week:1224,
OUT3FA_5:65,
IN1:85,
Total_IN1:100
},
{
周:1225,
OUT3FA_5:30,
IN1:40,
Total_IN1:120
}
]
}
有没有办法使用Python格式化json输出,以获得我想要的东西?
我做:
打印json.dumps(celldict)
/ pre>
得到我的输出。
任何帮助都将不胜感激。解决方案只要把
celldict
另一个dict:json.dumps({'success':True,数据':celldict.values()})
你必须添加
星期
键到celldict
首字母:for d in celldict.itervalues():
celldict ['Week'] ='1238'
或使用每个dict的副本即时创建:
json.dumps({' success':True,'data':[dict(d,Week ='1238')for d in celldict.values()]})
后一种方法,具有一些缩进,产生:
>>>打印json.dumps({'成功':True,'data':celldict.values()中的d的[dict(d,Week ='1238')}},indent = 4)
{
data:[
{
OUT3FA_5:24,
Week:1238,
Total_IN1:22,
IN1 :59
},
{
OUT3FA_5:12,
周:1238,
Total_IN1:37,
IN1:37
}
],
success:true
}
在线之间读取,似乎就像你的
1224
和1225
输入的例子实际上是你所指的周数。如果是这样,它们很容易被纳入:json.dumps({'success':True,'data':[dict d,Week = k)for k,d in celldict.iteritems()]})
会产生:
$ b{
data:[
{
OUT3FA_5
周:1225,
Total_IN1:22,
IN1:59
},
{
OUT3FA_5 12,
周:1224,
Total_IN1:37,
IN1:37
}
],
成功:true
}
I have written a Python script that outputs a long data structure (dictionary i called "celldict") in Json format. Here's a small part of it :
{ "1224": { "OUT3FA_5": 12, "IN1": 37, "Total_IN1": 37 }, "1225": { "OUT3FA_5": 24, "IN1": 59, "Total_IN1": 22 } }
But what I would like to do is have something like this :
{ "success": true, "data": [ { "Week":"1224", "OUT3FA_5": 65, "IN1": 85, "Total_IN1": 100 }, { "Week":"1225", "OUT3FA_5": 30, "IN1": 40, "Total_IN1": 120 } ] }
Is there a way to format the json output with Python to get I what I want? I do:
print json.dumps(celldict)
to get my output. Any help would be much much appreciated.
解决方案Just put
celldict
inside another dict:json.dumps({'success': True, 'data': celldict.values()})
You'll have to add the
Week
key to thecelldict
dictionaries first:for d in celldict.itervalues(): celldict['Week'] = '1238'
or use create a copy of each dict on-the-fly:
json.dumps({'success': True, 'data': [dict(d, Week='1238') for d in celldict.values()]})
The latter method, with some indentation, produces:
>>> print json.dumps({'success': True, 'data': [dict(d, Week='1238') for d in celldict.values()]}, indent=4) { "data": [ { "OUT3FA_5": 24, "Week": "1238", "Total_IN1": 22, "IN1": 59 }, { "OUT3FA_5": 12, "Week": "1238", "Total_IN1": 37, "IN1": 37 } ], "success": true }
Reading between the lines, it seems as if the
1224
and1225
keys in your input example are actually the week numbers you are referring to. If so, they are easily incorporated:json.dumps({'success': True, 'data': [dict(d, Week=k) for k, d in celldict.iteritems()]})
would produce:
{ "data": [ { "OUT3FA_5": 24, "Week": "1225", "Total_IN1": 22, "IN1": 59 }, { "OUT3FA_5": 12, "Week": "1224", "Total_IN1": 37, "IN1": 37 } ], "success": true }
这篇关于格式python输出到json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!