Python processes JSON data-world country Dimension Data

Source: Internet
Author: User
Tags python script timedelta

1. Preparing the country's JSON data

Put the prepared JSON data in the specified directory, where you can download it again

2. Test writing Python script to process JSON fetch field values
#Coding:utf8ImportTime , RE, OS, sys, time,urllib2,shutil,stringImportJson,datetime#set UTF-8 encoding formatReload (SYS) sys.setdefaultencoding ("Utf-8" )#gets the first n days of the current datedefGetbeforeday (n=0): Now_time=Datetime.datetime.now () beforeday= Now_time-Datetime.timedelta (n)returnBeforeday.strftime ("%y%m%d") Scriptdir=OS.GETCWD ()ifLen (SYS.ARGV) > 1: job_date_id= Sys.argv[1]Else: job_date_id=getbeforeday (0)Print "Current script path:%s, current parameter date:%s"%(scriptdir,job_date_id) Srcdata='{"area": "390,580", "Code": "263", "en": "Zimbabwe", "CN": "Zimbabwe", "ISO2": "ZW", "ISO3": "ZWE", "Population": " 11,651,858 "}'Jsondata=json.loads (srcdata)Printtype (jsondata)Print "##### #遍历key, values######" forKeyinchJsondata.keys ():PrintKey":", Jsondata[key]Print "# # # #或者指定key, return results # # #"Printjsondata['Code'],jsondata['cn'],jsondata['en'],jsondata[' Area'],jsondata['population']

3. Read text loop traversal fetch field value
#Coding:utf8Importrequests, JSON, time, RE, OS, sys, time,urllib2,shutil,stringImportJson,datetime#set UTF-8 encoding formatReload (SYS) sys.setdefaultencoding ("Utf-8" )#Read File contentsdefgetlines (filename): File_object= open (filename,'RB') Lines=File_object.readlines ()returnLines#return canonical stringdefGetformatecontext (*name): Format=','Context=Name[0] forIinchName[1:]: Context= context + format +Str (i) Context= str (context). replace ('(','('). Replace (')',')'). Replace (',',','). Replace (':',':')    returnContextdefGetbeforeday (n=0): Now_time=Datetime.datetime.now () beforeday= Now_time-Datetime.timedelta (n)returnBeforeday.strftime ("%y%m%d")#Write a filedefWrite (filename,context,model='a'):    #Remove First spacefilename =Filename.strip ()#Read Directory namePath =os.path.dirname (filename)#Create a directory if the directory does not exist    if  notos.path.exists (path):Pass    #Read file nameName =os.path.basename (filename) FP=Open (Filename,model) fp.write (context+'\ n') fp.close () Scriptdir=OS.GETCWD ()ifLen (SYS.ARGV) > 1: job_date_id= Sys.argv[1]Else: job_date_id= Getbeforeday (10)Print "Current script path:%s, current parameter date:%s"%(scriptdir,job_date_id) filename="%s\/jsondata\/country.json"%(Scriptdir) forLineinchgetlines (filename): line=Line.strip () Line= Line[1:] Line= Line[:-2]     forValueinchLine.split ("},"): Srcdata= value+"}"        #Print Srcdata        PrintSrcdata Jsondata=json.loads (srcdata)#Country CodeCode = jsondata['Code']        #Country Chinese nameCN = jsondata['cn']        #name of country in EnglishEn = jsondata['en']        #AreaArea = jsondata[' Area'].replace (',',"')        #populationPopulation = jsondata['population'].replace (',',"')        #ISO2ISO2 = jsondata['ISO2']        #ISO3ISO3 = jsondata['ISO3']        #Print CODE,CN,EN,AREA,POPULATION,ISO2,ISO3Context =Getformatecontext (CODE,CN,EN,AREA,POPULATION,ISO2,ISO3)PrintContext Write ("Country.csv", Context, model='a')
4. Final processing of data results

CSV format:

Excel format:

Python processes JSON data-world country Dimension Data

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.