2013-04-25 71 views
0

我想从json数据中提取一些信息。在下面的代码中,我首先提取包含我想要的信息的json数据部分,然后将它存储在一个文件中。然后我试图打开这个文件,我得到了我的代码后面的错误。你能帮我找到我错在哪里吗?如何从json中提取信息?

import json 
import re 

input_file = 'path' 
text = open(input_file).read() 
experience = re.findall(r'Experience":{"positionsMpr":{"showSection":true," (.+?),"visible":true,"find_title":"Find others',text) 
output_file = open ('/home/evi.nastou/Documenten/LinkedIn_data/Alewijnse/temp', 'w') 
output_file.write('{'+experience[0]+'}') 
output_file.close() 

text = open('path/temp') 
input_text = text.read() 
data = json.load(input_text) 
positions = json.dumps([s['companyName'] for s in data['positions']]) 
print positions 

错误:

Traceback (most recent call last): 
    File "test.py", line 13, in <module> 
    data = json.load(input_text) 
    File "/home/evi.nastou/.pythonbrew/pythons/Python-2.7.2/lib/python2.7/json/__init__.py", line 274, in load 
    return loads(fp.read(), 
AttributeError: 'str' object has no attribute 'read' 
+0

您尝试加载为字典的文档可能不是JSON或Python文档,或者它包含密钥中的非法字符。 – 2013-04-25 10:48:42

回答

3

你想用json.loads()(注意s)文件对象,而不是.read()结果,通:

text = open('path/temp') 
data = json.load(text) 

json.load()需要一个打开的文件对象,但你传递一个字符串; json.loads()需要一个字符串。