simplejson.dumps不接受字符串格式

时间:2014-02-19 02:17:53

标签: python json python-2.7

simplejson.dumps的工作原理如下:

package_specs=
{"Starter":{"QUOTA":1000,"BANDWIDTH":10000,"EMAILS":1000,"ADDONS":0,"PARKED":0,"SUBS":1000,"DBS":1000},
"Test":{"QUOTA":555,"BANDWIDTH":6666,"EMAILS":444,"ADDONS":33,"PARKED":22,"SUBS":77,"DBS":888},
"Default":{"QUOTA":1000,"BANDWIDTH":10000,"EMAILS":10,"ADDONS":0,"PARKED":0,"SUBS":0,"DBS":5}}

但不是package_specs作为从程序返回的字符串,它生成包规范,如下所示:

package_specs=
'{"Starter":{"QUOTA":1000,"BANDWIDTH":10000,"EMAILS":1000,"ADDONS":0,"PARKED":0,"SUBS":1000,"DBS":1000},
"Test":{"QUOTA":555,"BANDWIDTH":6666,"EMAILS":444,"ADDONS":33,"PARKED":22,"SUBS":77,"DBS":888},
"Default":{"QUOTA":1000,"BANDWIDTH":10000,"EMAILS":10,"ADDONS":0,"PARKED":0,"SUBS":0,"DBS":5}}'

页面上的结果是:

Default
0 {
1 "
2 Q
3 U
4 O
5 T
6 A
7 "
8 :
9 1
10 0
11 0
12 0
13 ,
14 "
15 B
16 A
17 N
18 D
19 W
20 I
21 D
22 T
23 H
etc.

在我的渲染函数中,要将json转储传递给mako模板,我有:

package_specs=simplejson.dumps(package_specs,sort_keys=True),

如何以json所需的格式获取package_specs?

我尝试了一个字典,但这也不起作用。

1 个答案:

答案 0 :(得分:2)

第一个例子是JSON,第二个例子是string representation of JSON

将json转换为使用json.dumps

的字符串
json.dumps({"foo": "bar"})

将字符串转换为json,使用json.loads

json.loads('{"foo": "bar"}')