Python JSON 编码

发布于 2024-07-23 23:17:39 字数 652 浏览 15 评论 0原文

我正在尝试用 Python 将数据编码为 JSON,但遇到了很多麻烦。 我相信这个问题只是一个误解。

我对 Python 比较陌生,从来没有真正熟悉过各种 Python 数据类型,所以这很可能是让我困惑的原因。

目前,我正在声明一个列表,循环遍历另一个列表,并将一个列表附加到另一个列表中:

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"}}

所以我要么:

  • 我不理解 JSON 语法
  • 我不理解 Python JSON 模块
  • 我正在使用不适当的数据类型。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

你又不是我 2024-07-30 23:17:39

Python 列表 转换为 JSON 数组。 它为您提供的是一个完全有效的 JSON 字符串,可以在 Javascript 应用程序中使用。 为了获得您所期望的结果,您需要使用 dict

>>> json.dumps({'apple': 'cat', 'banana':'dog', 'pear':'fish'})
'{"pear": "fish", "apple": "cat", "banana": "dog"}'

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"}'
素染倾城色 2024-07-30 23:17:39

我认为您只是在交换转储负载

>>> import json
>>> data = [['apple', 'cat'], ['banana', 'dog'], ['pear', 'fish']]

第一个以(JSON 编码)字符串形式返回其数据参数:

>>> encoded_str = json.dumps( data )
>>> encoded_str
'[["apple", "cat"], ["banana", "dog"], ["pear", "fish"]]'

第二个则相反,返回与其(JSON 编码)字符串参数相对应的数据:

>>> decoded_data = json.loads( encoded_str )
>>> decoded_data
[[u'apple', u'cat'], [u'banana', u'dog'], [u'pear', u'fish']]
>>> decoded_data == data
True

I think you are simply exchanging dumps and loads.

>>> import json
>>> data = [['apple', 'cat'], ['banana', 'dog'], ['pear', 'fish']]

The first returns as a (JSON encoded) string its data argument:

>>> encoded_str = json.dumps( data )
>>> encoded_str
'[["apple", "cat"], ["banana", "dog"], ["pear", "fish"]]'

The second does the opposite, returning the data corresponding to its (JSON encoded) string argument:

>>> decoded_data = json.loads( encoded_str )
>>> decoded_data
[[u'apple', u'cat'], [u'banana', u'dog'], [u'pear', u'fish']]
>>> decoded_data == data
True
泅渡 2024-07-30 23:17:39

simplejson(或 Python 2.6 及更高版本中的库 json)中,loads 接受 JSON 字符串并返回 Python 数据结构,dumps 采用 Python 数据结构并返回 JSON 字符串。 JSON 字符串可以编码 Javascript 数组,而不仅仅是对象,Python 列表对应于编码数组的 JSON 字符串。 JSON 字符串(例如

{"apple":"cat", "banana":"dog"}

要获取传递给 json.dumps

dict(apple="cat", banana="dog")

Python 对象),可以是:尽管 JSON 字符串对于相同的 dict 也是有效的 Python 语法。 然而,我相信您所说的特定字符串只是无效的 JSON 语法。

In simplejson (or the library json in Python 2.6 and later), loads takes a JSON string and returns a Python data structure, dumps takes a Python data structure and returns a JSON string. JSON string can encode Javascript arrays, not just objects, and a Python list corresponds to a JSON string encoding an array. To get a JSON string such as

{"apple":"cat", "banana":"dog"}

the Python object you pass to json.dumps could be:

dict(apple="cat", banana="dog")

though the JSON string is also valid Python syntax for the same dict. I believe the specific string you say you expect is simply invalid JSON syntax, however.

烟织青萝梦 2024-07-30 23:17:39

您正在编码的数据是无键数组,因此 JSON 使用 [] 括号对其进行编码。 有关详细信息,请参阅 www.json.org。 大括号用于带有键/值对的列表。

来自 www.json.org:

JSON 建立在两种结构之上:

名称/值对的集合。 在
各种语言,这被实现为
对象、记录、结构、字典、
哈希表、键控列表或关联表
大批。 值的有序列表。 在
大多数语言,这是实现为
数组、向量、列表或序列。

对象是一组无序的对象
名称/值对。 一个对象开始
以 {(左大括号)并以 } 结尾
(右大括号)。 每个名字后面都有
by :(冒号)和名称/值对
用 ,(逗号)分隔。

数组是有序集合
价值观。 数组以 [ 开头(左
括号)并以](右
括号)。 值由 , 分隔
(逗号)。

The data you are encoding is a keyless array, so JSON encodes it with [] brackets. See www.json.org for more information about that. The curly braces are used for lists with key/value pairs.

From www.json.org:

JSON is built on two structures:

A collection of name/value pairs. In
various languages, this is realized as
an object, record, struct, dictionary,
hash table, keyed list, or associative
array. An ordered list of values. In
most languages, this is realized as an
array, vector, list, or sequence.

An object is an unordered set of
name/value pairs. An object begins
with { (left brace) and ends with }
(right brace). Each name is followed
by : (colon) and the name/value pairs
are separated by , (comma).

An array is an ordered collection of
values. An array begins with [ (left
bracket) and ends with ] (right
bracket). Values are separated by ,
(comma).

不乱于心 2024-07-30 23:17:39

JSON 使用方括号表示列表 ( [ "one", "two", "third" ] ),使用大括号表示键/值字典(在 JavaScript 中也称为对象,{"one" :1, "二":"b"})。

转储是非常正确的,您得到了一个包含三个元素的列表,每个元素都是一个包含两个字符串的列表。

如果你想要一本字典,也许是这样的:

x = simplejson.dumps(dict(data))
>>> {"pear": "fish", "apple": "cat", "banana": "dog"}

你期望的字符串 ('{{"apple":{"cat"},{"banana":"dog"}}') 不是有效的 JSON。 A

JSON uses square brackets for lists ( [ "one", "two", "three" ] ) and curly brackets for key/value dictionaries (also called objects in JavaScript, {"one":1, "two":"b"}).

The dump is quite correct, you get a list of three elements, each one is a list of two strings.

if you wanted a dictionary, maybe something like this:

x = simplejson.dumps(dict(data))
>>> {"pear": "fish", "apple": "cat", "banana": "dog"}

your expected string ('{{"apple":{"cat"},{"banana":"dog"}}') isn't valid JSON. A

月野兔 2024-07-30 23:17:39

因此, simplejson.loads 接受一个 json 字符串并返回一个数据结构,这就是您在那里收到该类型错误的原因。

simplejson.dumps(data) 返回

'[["apple", "cat"], ["banana", "dog"], ["pear", "fish"]]'

Which is a json array,这就是你想要的,因为你给了它一个 python 数组。

如果你想获得一个“对象”类型语法,你可以这样做

>>> data2 = {'apple':'cat', 'banana':'dog', 'pear':'fish'}
>>> simplejson.dumps(data2)
'{"pear": "fish", "apple": "cat", "banana": "dog"}'

,JavaScript 将作为一个对象出现。

So, simplejson.loads takes a json string and returns a data structure, which is why you are getting that type error there.

simplejson.dumps(data) comes back with

'[["apple", "cat"], ["banana", "dog"], ["pear", "fish"]]'

Which is a json array, which is what you want, since you gave this a python array.

If you want to get an "object" type syntax you would instead do

>>> data2 = {'apple':'cat', 'banana':'dog', 'pear':'fish'}
>>> simplejson.dumps(data2)
'{"pear": "fish", "apple": "cat", "banana": "dog"}'

which is javascript will come out as an object.

来日方长 2024-07-30 23:17:39

尝试:

import simplejson
data = {'apple': 'cat', 'banana':'dog', 'pear':'fish'}
data_json = "{'apple': 'cat', 'banana':'dog', 'pear':'fish'}"

simplejson.loads(data_json) # outputs data
simplejson.dumps(data) # outputs data_joon

注意:基于 Paolo 的回答。

Try:

import simplejson
data = {'apple': 'cat', 'banana':'dog', 'pear':'fish'}
data_json = "{'apple': 'cat', 'banana':'dog', 'pear':'fish'}"

simplejson.loads(data_json) # outputs data
simplejson.dumps(data) # outputs data_joon

NB: Based on Paolo's answer.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文