亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

訪問JSON文件python if語句

訪問JSON文件python if語句

慕沐林林 2023-05-09 10:18:11
我正在嘗試根據 JSON 文件中的用戶信息在 if 語句中訪問我的 JSON 文件中的信息。所以我決定通過讓它向控制臺打印一條消息來測試它。但是,它甚至根本不讀取 JSON 文件。這是 JSON 文件{    "member_acct":{       "email":"[email protected]",       "password":"examplepassword"    },    "product_info":{       "product_name":"Nike Airforce 1s",       "W/M":"M",       "size":"9.5"    } }這是蟒蛇。我正在使用嵌套的 if 語句 我想知道我是否可以將這些 if 語句組合起來:json_data = json.load(f)# Women's shoe sizesa = json_data["product_info"]["W/M"]if 'W' in a:    print("This is a womens shoe")    if 5 in json_data["product_info"]["size"]:        print("size 5")    else        print("This is not a size 5")// men sizes b = json_data["product_info"]["W/M"]if "M" in b:     print ("this is a men's shoe")    if "3.5" in json_data["product_info"]["size"]:      print ("3.5")    else print ("this is not a size 3.5")
查看完整描述

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 大小值是浮點數,而不是整數。調整為將值轉換為浮動


查看完整回答
反對 回復 2023-05-09
  • 1 回答
  • 0 關注
  • 157 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號