Python JSON编码 [英] Python JSON encoding
问题描述
我对Python来说比较新,从来没有真正熟悉各种Python数据类型,所以这很可能是让我烦恼的。
目前,我正在声明一个列表,循环和另一个列表,并在另一个列表中添加一个列表:
import simplejson,json
data = [['apple','cat'],['banana','dog'],['pear','fish']]
x = simplejson.loads(data)
#>>> typeError:expected string或buffer ..
x = simplejson.dumps(stream)
#>>> [[apple,cat],[banana,dog],[pear,fish]]
# - 不应该使用JSON编码的字符串:{{apple :{cat},{banana:dog}}
:
- 我不明白JSON语法
- 我不明白Pythons JSON模块(s)
- 我使用的是不当的数据类型。
Python 列表
转换为JSON 数组
。它给你的是一个完全有效的JSON字符串,可以在Javascript应用程序中使用。要获得预期,您需要使用 dict
:
>>> json.dumps({'apple':'cat','banana':'dog','pear':'fish'})
'{pear:fish,apple ,香蕉:狗}'
I'm trying to encode data to JSON in Python and I been having a quite a bit of trouble. I believe the problem is simply a misunderstanding.
I'm relatively new to Python and never really got familiar with the various Python data types, so that's most likely what's messing me up.
Currently I am declaring a list, looping through and another list, and appending one list within another:
import simplejson, json
data = [['apple', 'cat'], ['banana', 'dog'], ['pear', 'fish']]
x = simplejson.loads(data)
# >>> typeError: expected string or buffer..
x = simplejson.dumps(stream)
# >>> [["apple", "cat"], ["banana", "dog"], ["pear", "fish"]]
# - shouldn't JSON encoded strings be like: {{"apple":{"cat"},{"banana":"dog"}}
So I either:
- I don't understand JSON Syntax
- I don't understand the Pythons JSON module(s)
- I'm using an inappropriate data type.
Python lists
translate to JSON arrays
. What it is giving you is a perfectly valid JSON string that could be used in a Javascript application. To get what you expected, you would need to use a dict
:
>>> json.dumps({'apple': 'cat', 'banana':'dog', 'pear':'fish'})
'{"pear": "fish", "apple": "cat", "banana": "dog"}'
这篇关于Python JSON编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!