猿问

访问JSON文件python if语句

我正在尝试根据 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 sizes


a = 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")


慕沐林林
浏览 141回答 1
1回答

一只甜甜圈

如果您在单独的文件中有 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.pyimport 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 大小值是浮点数,而不是整数。调整为将值转换为浮动
随时随地看视频慕课网APP

相关分类

Python
我要回答