JSON转换为数组Python [英] JSON to arrays Python
本文介绍了JSON转换为数组Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在互联网上搜索,但没有成功,但它是使用JSON文件将JSON信息设置为数组的一种方法,例如:
I searched on internet, without success, a way to set JSON infos into arrays, with a JSON file like:
{ "_links": {}, "chatter_count": 3, "chatters": { "moderators": ["nightbot", "mistercraft"], "staff": [], "admins": [], "global_mods": [], "viewers": [] } }
在代码中,例如当我输入
And in the code, when I put for example
Print(moderators)
或
Print(*Filename*.moderators())
代码向我显示["nightbot", "mistercraft"]
感谢帮助
推荐答案
以下是将Json文件转换为python变量的好方法:
Here is the good way to convert a Json file to python variable:
import json
data = None
with open('/path/to/your/file/here.json', 'r') as fd:
data = json.loads(fd.read())
print data["chatters"]["moderators"]
以下是代码的作用:
下面的代码从给定路径打开文件,读取所有内容并将其转换为dict()对象,该对象是python默认类型(
The code below open the file from the given path, read all the content and convert it into a dict() object which is a python default type (https://docs.python.org/2/library/stdtypes.html#dict).
您还可以直接从字符串中解析json:
You can also parse json directly from a string:
import json
json_str = '{ "_links": {}, "chatter_count": 3, "chatters": { "moderators": ["nightbot", "mistercraft"], "staff": [], "admins": [], "global_mods": [], "viewers": [] } }'
data = json.loads(json_str)
print data["chatters"]["moderators"]
这篇关于JSON转换为数组Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文