Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
291 views
in Technique[技术] by (71.8m points)

Python: extracting an integer from json using split

I'm trying to extract the month number from dates in JSON files as an integer. The dates are formatted like this: "1990-12-01" The problem is that I'm getting extra characters that are incompatible with integers. I'm obviously missing something dumb. Here's an example of my output:

['12']

Here's my code:

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

And here's what the JSON looks like:

{
  "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"
    }
  } ]
}

What can I do to produce output that's pure integers? Thanks,


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

just cast to int and extreact item from list because when slicing with [1:2] you slice notation returns a list:

so do:

print(int(newmonth[0]))

or just refactor the code even better:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...