2017-02-20 98 views
0

編寫一個輸入JSON文件的程序(格式如 example1.json)並打印出標題字段的值。如何輸入JSON文件並打印一行

import json 

# TODO: Read your json file here and return the contents 
def read_json(filename): 
    dt = {} 
    # read the file and store the contents in the variable 'dt' 
    with open(filename,"r") as fh: 
     dt = json.load(fh) 

    ###fh = open(filename, "r") 
    ###dt = json.load(fh) 

    return dt 


# TODO: Pass the json file here and print the value of title field. Remove the `pass` statement 
def print_title(dt): 
    print filename["title"] 


# TODO: Input a file from the user 
filename = raw_input("Enter the JSON file: ") 


# The function calls are already done for you 
r = read_json(filename) 
print_title(r) 

嗨,我是新來的Python,我不知道我做錯了什麼。我不斷收到以下消息: enter image description here

+0

你回溯是*文字*,請不要使用截圖作爲無法搜索或複製到一個編輯器。 –

+0

您正在嘗試「打印」文件名而不是解析的數據。嘗試用'print(dt [「title」])替換'print filename [「title」]''' – zwer

回答

2

你幾乎在那裏,你只是混淆了參數名稱。

更改此:

def print_title(dt): 
    print filename["title"] 

要:

def print_title(dt): 
    print dt["title"] 
+0

謝謝! – helpmeplease

+0

@helpmeplease,不客氣 –

+0

7-8行和10-11行有什麼區別?他們都似乎做同樣的事情 – helpmeplease