2011-09-27 45 views
2
Input : {"id": null, "type": null, "order_for": null, "name": "Name"} 

代碼:Python的simplejson.dumps仍返回字符串

input_map = simplejson.dumps(eval(line)) 
print type(input_map) 

回報

<type 'str'> 

什麼在這裏錯了嗎?

謝謝

+1

沒什麼,'dumps'需要一些輸入,並將其轉換成JSON:* 「序列化'obj'以JSON格式'str'。」 *。 –

+0

我看到這個我試圖打印K,V對=> AttributeError:'STR'對象沒有屬性'項目' – daydreamer

回答

4

也許你的意思是:

print(input_map) 

另外,如果你使用nulllineeval應該提出一個NameError。 你可以使用simplejson.loads來代替:

import simplejson 
line='{"id": null, "type": null, "order_for": null, "name": "Name"}' 
input_map = simplejson.loads(line) 
print(input_map) 
# {u'order_for': None, u'type': None, u'id': None, u'name': u'Name'} 

print(simplejson.dumps(input_map)) 
# {"order_for": null, "type": null, "id": null, "name": "Name"} 
+1

完美,這是我失蹤的地方,我需要json.dumps over json.loads輸出,謝謝lot – daydreamer

+0

@daydreamer:我不確定這是否是你需要的(或者我誤解了你)。如果你在'loads'的輸出上應用'dumps',你會得到和你原來的輸入相同的結果。 –

+0

@FelixKling,所有我想要一個JSON對象,我的輸入字符串,上面提到的方式讓我這樣做 – daydreamer