Python JSON编码 [英] Python JSON encoding

查看:140
本文介绍了Python JSON编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在Python中将数据编码为JSON,而且我遇到了一些麻烦。我相信这个问题只是一个误会。



我对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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆