1 回答

TA貢獻1836條經驗 獲得超5個贊
如果您在單獨的文件中有 JSON,則需要讀取該文件才能導入with open('./data.json') as f. 此外,if 'W' in a似乎不正確,因為您的 JSON blob 將其作為 string 而不是 object "W/M":"M"。所以它看起來像:
data.json
{
"member_acct":{
"email":"[email protected]",
"password":"examplepassword"
},
"product_info":{
"product_name":"Nike Airforce 1s",
"W/M":"M",
"size":"9.5"
}
}
main.py
import json
with open('./data.json') as f:
data = json.load(f)
a = data["product_info"]["W/M"]
# the value of a is a string and not a dictionary
if a == 'W':
print("This is a woman's shoe")
# the value of this is a string and not a dictionary
if float(data["product_info"]["size"]) == 5:
print("size 5")
else:
print("This is not a size 5")
else:
print ("this is a men's shoe")
if float(data["product_info"]["size"]) == 3.5:
print("size 3.5")
else:
print("This is not a size 3.5")
注意:已編輯,不錯,JSON 大小值是浮點數,而不是整數。調整為將值轉換為浮動
添加回答
舉報