如何将json文件读入python?

时间:2016-09-09 21:10:44

标签: python json spark-dataframe

我是JSON和Python的新手,对此的任何帮助都将非常感激。

我读过关于json.loads的内容,但很困惑

如何使用json.loads将文件读入Python?

以下是我的JSON文件格式:

{
        "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)]这样的新列表中。新列表将用于创建火花数据框。

2 个答案:

答案 0 :(得分:2)

打开文件,获取文件句柄:

fh = open('thefile.json')

https://docs.python.org/2/library/functions.html#open

然后,将文件句柄传递给json.load():(不要使用加载 - 这是字符串)

import json
data = json.load(fh)

https://docs.python.org/2/library/json.html#json.load

从那里,您可以轻松处理代表您的json编码数据的python字典。

new_list = [(detail['abc'], detail['def']) for detail in data['details']]

请注意,您的JSON格式也是错误的。你需要在许多地方使用逗号分隔符,但这不是问题。

答案 1 :(得分:2)

我试图尽可能地理解你的问题,但看起来格式很差。

首先关闭你的json blob是无效的json,它缺少相当多的逗号。这可能就是你要找的东西:

{
    "header": {
        "platform": "atm",
        "version": "2.0"
    },
    "details": [
        {
            "abc": "3",
            "def": "4"
        },
        {
            "abc": "5",
            "def": "6"
        },
        {
            "abc": "7",
            "def": "8"
        }
    ]
}

现在假设您正在尝试在python中解析它,您将不得不执行以下操作。

import json

json_blob = '{"header": {"platform": "atm","version": "2.0"},"details": [{"abc": "3","def": "4"},{"abc": "5","def": "6"},{"abc": "7","def": "8"}]}'
json_obj = json.loads(json_blob)

final_list = []

for single in json_obj['details']:
    final_list.append((int(single['abc']), int(single['def'])))

print(final_list)

这将打印以下内容:[(3,4),(5,6),(7,8)]

相关问题