为了账号安全,请及时绑定邮箱和手机立即绑定

访问JSON文件python if语句

访问JSON文件python if语句

慕沐林林 2023-05-09 10:18:11
我正在尝试根据 JSON 文件中的用户信息在 if 语句中访问我的 JSON 文件中的信息。所以我决定通过让它向控制台打印一条消息来测试它。但是,它甚至根本不读取 JSON 文件。这是 JSON 文件{    "member_acct":{       "email":"example@gmail.com",       "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":"example@gmail.com",

       "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 关注
  • 102 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信