2013-04-25 5 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 

오류 :

대신 .read()의 결과의 파일 객체, 또는은 패스합니다 ( s 주) json.loads()를 사용하려면
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 문서가 아니거나 키에 불법 문자가 포함되어있을 수 있습니다. –

답변

3

:

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

json.load()을 열려있는 파일 객체를 사용하지만 문자열을 전달하고 있습니다. json.loads()은 문자열을 취합니다.

관련 문제