2016-09-09 37 views
-3

我是JSON和Python的新手,对此非常感激。如何将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" 
     }  
     ] 
    } 

我的要求是详细阅读所有​​"def"的值,并添加这是一个新的列表这样[(1,2),(3,4),(5,6),(7,8)]。新列表将用于创建火花数据框。

+1

看来你忘了,包括在你的问题的问题。 – Biffen

+0

你的问题是什么,你尝试了什么? – wander95

+0

我如何在Python中实现上述功能。我读了关于json.loads,但很困惑: –

回答

1

打开文件,并得到一个文件句柄:

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

我试图尽可能了解您的问题,但它看起来像格式不好。

首先你的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)]

+0

由于提到了FlipMcF,如果您正在从文件中读取数据,json.load()将处理像读取这样的文件,这在python文档中有提到 – JJK

+0

非常感谢!阅读卡夫卡队列中的消息 –