http://www.learnpython.org/Serialization_using_JSON_and_pickle卡住使用JSON
這裏有操作的指令:
該練習的目的是要打印出JSON字符串鍵值對「Me」是:800添加到它。
下面是我們應該修改的起始代碼。
#Exercise fix this function, so it adds the given name and salary pair to the json it returns
def add_employee(jsonSalaries, name, salary):
# Add your code here
return jsonSalaries
#Test code - shouldn't need to be modified
originalJsonSalaries = '{"Alfred" : 300, "Jane" : 301 }'
newJsonSalaries = add_employee(originalJsonSalaries, "Me", 800)
print(newJsonSalaries)
我完全失去了。 JSON課程最好是簡短的。我似乎在這裏運行的問題是,orginalJsonSalaries
被定義爲一個字符串(包含括號等所有不必要的符號。事實上,我認爲如果圍繞其定義的單引號被刪除,originalJsonSalaries
將是一本字典,而這會輕鬆很多。但因爲它的立場,我怎麼能追加"Me"
和800
字符串,並仍然保持字典的格式化?
是的,我非常非常新的編碼。唯一的其他語言我所知道的是TCL
編輯:
OK,感謝答案,我想通了,我被緻密我寫了這樣的代碼:
import json
#Exercise fix this function, so it adds the given name and salary pair to the json it returns
def add_employee(jsonSalaries, name, salary):
# Add your code here
jsonSalaries = json.loads(jsonSalaries)
jsonSalaries["Me"] = 800
return jsonSalaries
#Test code - shouldn't need to be modified
originalJsonSalaries = '{"Alfred" : 300, "Jane" : 301 }'
newJsonSalaries = add_employee(originalJsonSalaries, "Me", 800)
print(newJsonSalaries)
這是行不通的。無論出於何種原因,原來的字典鍵被格式化爲Unicode(我不知道發生的地點),所以當我打印出來的字典中,「U」顯示標誌:
{u'Jane': 301, 'Me': 800, u'Alfred': 300}
我已經嘗試使用dict.pop()
取代密鑰(dict("Jane") = dict.pop(u"Jane")
)但只是提出SyntaxError: can't assign to function call
是我原來的解決方案不正確,或者這是一些煩人的格式問題,以及如何解決它?
將JSON轉換成字典,將「Me」和「800」值添加到字典中,然後將字典轉換回JSON字符串。如果您不確定如何將值添加到字典中,請嘗試打印字典以查看它的外觀。祝好運並玩得開心點。 – steveha
是的,我很笨。但是,我擁有的「簡單」解決方案無效。字典鍵被格式化爲unicode,所以當我打印它時,會顯示'u'標誌。我將我的代碼和結果顯示爲對原始問題的編輯。 – jktstance