如何将json文件读入python? [英] How do I read a json file into python?
问题描述
我是 JSON 和 Python 的新手,对此的任何帮助将不胜感激.
I'm new to JSON and Python, any help on this would be greatly appreciated.
我读过 json.loads 但很困惑
I read about json.loads but am confused
如何使用 json.loads 将文件读入 Python?
How do I read a file into Python using json.loads?
以下是我的 JSON 文件格式:
Below is my JSON file format:
{
"header": {
"platform":"atm"
"version":"2.0"
}
"details":[
{
"abc":"3"
"def":"4"
},
{
"abc":"5"
"def":"6"
},
{
"abc":"7"
"def":"8"
}
]
}
我的要求是详细读取所有 "abc"
"def"
的值并将其添加到这样的新列表中 [(1,2),(3,4),(5,6),(7,8)]
.新列表将用于创建 spark 数据框.
My requirement is to read the values of all "abc"
"def"
in details and add this is to a new list like this [(1,2),(3,4),(5,6),(7,8)]
. The new list will be used to create a spark data frame.
推荐答案
打开文件,获取文件句柄:
Open the file, and get a filehandle:
fh = open('thefile.json')
https://docs.python.org/2/library/functions.html#open
然后,将文件句柄传递给 json.load() :(不要使用负载 - 那是用于字符串)
Then, pass the file handle into json.load(): (don't use loads - that's for strings)
import json
data = json.load(fh)
https://docs.python.org/2/library/json.html#json.load
从那里,您可以轻松处理表示 json 编码数据的 Python 字典.
From there, you can easily deal with a python dictionary that represents your json-encoded data.
new_list = [(detail['abc'], detail['def']) for detail in data['details']]
请注意,您的 JSON 格式也是错误的.很多地方都需要逗号分隔符,但这不是问题.
Note that your JSON format is also wrong. You will need comma delimiters in many places, but that's not the question.
这篇关于如何将json文件读入python?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!