Python:使用拆分从 json 中提取整数

Python: extracting an integer from json using split

我正在尝试从 JSON 文件中的日期中提取月份数字作为整数。日期格式如下:"1990-12-01" 问题是我得到了与整数不兼容的额外字符。我显然错过了一些愚蠢的东西。这是我的输出示例:

['12']

这是我的代码:

f = open('data/file1.json')
data = json.load(f)
birthmonth = (data['people'][0]['birthDate'])
newmonth = birthmonth.split('-')[1:2]
print(newmonth)

下面是 JSON 的样子:

{
  "copyright" : "All Rights Reserved.",
  "people" : [ {
    "id" : 84755,
    "primaryNumber" : "21",
    "birthDate" : "1990-12-01",
    "currentAge" : 29,
    "active" : true,
    "currentRole" : {
      "id" : 1,
      "name" : "office"
    },
    "primaryBase" : {
      "code" : "R",
      "name" : "Recall"
    }
  } ]
}

如何生成纯整数输出? 谢谢,

只需转换为 int 并从列表中提取项目,因为当使用 [1:2] 切片时,您将符号 returns 切片为列表:

也一样:

print(int(newmonth[0]))

或者更好地重构代码:

with open('data/file1.json') as f:
    data = json.load(f)
    birthmonth = (data['people'][0]['birthDate'])
    newmonth =int(birthmonth.split('-')[1])
    print(newmonth)

切片符号 [1:2] returns 一个子列表,从索引 1 到 2(已排除),因此它需要您的数据,但作为列表,您最好使用这些选项之一

  • 日期操作,直接解析内容为date

    newmonth = datetime.strptime(birthmonth, "%Y-%m-%d").month
    
  • 字符串操作避免因为你不检查数据一致性

    • 拆分 dash,它给出了一个字符串列表,您需要从中获取第二个框

      birthmonth.split('-')                    # ['1990', '12', '01']
      birthmonth.split('-')[1]                 # '12'
      newmonth = int(birthmonth.split('-')[1]) # 12
      
    • 切片以检索字符串的特定部分

      birthmonth[5:7] # '12'
      newmonth = int(birthmonth[5:7]) # 12
      

使用正确的工具完成工作,strptime:

>>> from datetime import datetime
>>> datetime.strptime(data["people"][0]["birthDate"], "%Y-%m-%d").month
12

这为您提供了数据验证的额外好处。如果输入不是年-月-日格式,盲目地切片和拆分字符串可能会意外 return 虚假结果。