Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
297 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 Reply

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...