2016-05-31 29 views
-1

我在加載python中的JSON時遇到了問題。我正在使用Python 2.7,我有一個我想加載的JSON文件。我所做的:在python中加載JSON

movies = json.load(open(FBO_REF_FILE, 'r')) 

但是,當我顯示出來我有一個字典滿:

{u'id_yeyecine': 42753, u'budget_dollars': u'85', u'classification': u'Tous publics', u'pays': u'US', u'budget_euros': u'0', u'dpw_entrees_fr': 132326, u'realisateurs': u'Brad Peyton, Kevin Lima', u'is_art_et_essai': u'NON', u'distributeur_video': u'Warner hv', u'genre_gfk_1': u'ENFANT', u'genre_gfk_2': u'FILM FAMILLE', u'genre_gfk_3': u'FILM FAMILLE', u'is_3D': u'OUI', u'fid': 16429, u'cum_entrees_pp': 58076, u'titre': u'COMME CHIENS ET CHATS LA REVANCHE DE KITTY GALORE', u'psp_entrees': 963, u'cum_entrees_fr': 348225, u'dps_copies_fr': 453, u'dpj_entrees_pp': 7436, u'visa': 127021, u'dps_entrees_fr': 178908, u'genre': u'Com\xe9die', u'distributeur': u'WARNER BROS.', u'editeur_video': u'Warner bros', u'psp_copies': 15, u'dpw_entrees_pp': 26195, u'id_imdb': None, u'date_sortie_video': u'2010-12-06', u'dps_copies_pp': 39, u'date_sortie': u'2010-08-04', u'dps_entrees_pp': 32913, u'dpj_entrees_fr': 40369, u'ecrivains': u'', u'acteurs': u"Chris O'donnell, Jack McBrayer", u'is_premier_film': u'NON'} 

我試着用AST,但我得到了以下錯誤:字符串格式不正確。使用最後,當我得到的錯誤是:

153  if cursor is None: 
    154   movies = json.load(open(FBO_REF_FILE, 'r')) 
--> 155   movies = ast.literal_eval(movies) 
    156   for movie in movies: 
    157    if movies[movie]['id_allocine'] == allocine_id: 

/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ast.pyc in literal_eval(node_or_string) 
    78     return left - right 
    79   raise ValueError('malformed string') 
---> 80  return _convert(node_or_string) 
    81 
    82 

/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ast.pyc in _convert(node) 
    77    else: 
    78     return left - right 
---> 79   raise ValueError('malformed string') 
    80  return _convert(node_or_string) 
    81 

ValueError: malformed string 
+5

你如何「顯示」「電影」?這對我來說看起來很好:JSON按照預期被解析爲字典。 – 2016-05-31 13:06:55

+0

你能告訴我們該文件的內容嗎?也許你正在得到正確的結果 – juankysmith

+0

@LutzHorn我正在使用print來顯示它 – mel

回答

3

隨着json.load你解析JSON文件到Python的數據類型。在你的情況下,這是一個字典。

open加載文件。

如果你不想如果你想解析JSON文件到Python的數據類型來解析JSON文件只是以下

content = None 
with open(FBO_REF_FILE, 'r') as f: 
    content = f.read() 
print content # content is a string contaning the content of the file 

請執行以下操作:

content = None 
with open(FBO_REF_FILE, 'r') as f: 
    content = json.loads(f.read()) 
print content # content is a dict containing the parsed json data 
print content['id_yeyecine'] 
print content['budget_dollars'] 
2

閱讀從movies,請使用常規字典方法:

id_yeyecine = movies["id_yeyecine"] 

現在id_yeyecine42753