python - 需要 : simple way to force json to decode to "normal" iterable python lists

标签 python json list unicode iterable

我在 stackoverflow 上玩过很多次,以前从未发现有必要提出问题,虽然有很多关于这个主题的帖子,但我似乎找不到简单且有意义的东西。如果我以某种方式错过了某些内容,请提供链接。

这里是:我试图使用 json 在 python 客户端/服务器之间来回传递列表,但我将问题压缩成一个 block 来说明:

import json
testdata = ['word','is','bond', False, 6, 99]
# prints normal iterable list
print testdata

myjson = json.dumps(testdata)

#prints [u'word', u'is', u'bond', False, 6, 99], which contains unicode strings
print json.loads(myjson)

# Iterates over each character, since apparently, Python does recognize it is a list
for i in myjson:
    print i

这似乎是错误的。我传入了一个可迭代列表,但我得到了一些不能以这种方式使用的东西。我看到很多答案都建议我应该“处理 unicode”,如果我知道如何的话,这很好。我要么需要一种方法来强制 json 以 ascii 或 utf-8 或其他方式加载,要么需要一种方法来允许 python 正常迭代包含 unicode 字符串的列表。

谢谢!

最佳答案

问题是您正在迭代 myjson(字符串),而不是迭代 json.loads(myjson)(可迭代列表)的结果。

myjson = json.dumps(testdata)

mydata = json.loads(myjson)
#prints [u'word', u'is', u'bond', False, 6, 99], which contains unicode strings
print mydata
#prints ["word", "is", "bond", false, 6, 99], which is still just a string
print myjson

# Iterates over each character, since it's a string
for i in myjson:
    print i
# Iterates over the list
for i in mydata:
    print i

关于python - 需要 : simple way to force json to decode to "normal" iterable python lists,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18413569/

相关文章:

python - YAML - 转储没有类型/标签的嵌套对象

python - 沿指定轴的两个 3D 矩阵之间的 np.dot 乘积

.net - 针对.Net中的架构验证JSON

java - JSON对齐其循环相同的项目

vb.net - 如何将枚举添加到列表中

Java 惰性字符串流,包括 List<String>

python - 使用 nginx 和 gunicorn 运行 flask 应用程序

python - 使用python计算灰度图像中掩码的面积(以像素为单位)

javascript - 用jquery动态填充用户输入对应的json数据

python - 为什么此代码会更改两个列表(id 不相同)?