简体   繁体   中英

How to Loop through a dictionary in python and save results in JSON format - invalid format

I am looping through a list and then a dictionary in Python, storing the data in another dictionary, and writing the data to a json file using json.dump. My JSON output is a little off, with some extra braces and missing comments. Here is my loop:

for zip_code in zip_codes:
  for key, code in census_codes.iteritems():
      stats[key] = c.acs.zipcode(('NAME', code), zip_code)[0][code]

  zip_stats = {}
  zip_stats[zip_code] = stats
  json.dump(zip_stats, ofile, indent=4) 

Here is the output:

{
    "10001": {
        "total_population": "21097", 
        "widowed": "580", 
        "now_married": "4595", 
        "divorced": "4595", 
        "housing_units": "756", 
        "some_college": "2404", 
        "seperated": "346", 
        "hs_graduate": "1359", 
        "graduate": "4305", 
        "total_females": "11024", 
        "total_males": "10073", 
        "bachelors": "5705", 
        "average_age": "34.6", 
        "never_married": "11964"
    }
}{
    "10012": {
        "total_population": "28982", 
        "widowed": "1538", 
        "now_married": "14932", 
        "divorced": "14932", 
        "housing_units": "799", 
        "some_college": "2574", 
        "seperated": "136", 
        "hs_graduate": "2622", 
        "graduate": "6510", 
        "total_females": "14668", 
        "total_males": "14314", 
        "bachelors": "7275", 
        "average_age": "42.8", 
        "never_married": "4743"
    }
}

Why is json.dumps() not formatting the output as valid JSON?

Try:

zip_stats = {}
for zip_code in zip_codes:
    stats = {}
    for key, code in census_codes.iteritems():
        stats[key] = c.acs.zipcode(('NAME', code), zip_code)[0][code]
    zip_stats[zip_code] = stats
json.dump(zip_stats, ofile, indent=4) 

Your code created a new zip_stats dictionary for each zip_code , and wrote each as a separate JSON string. Mine creates the dictionary once, adds the 2 stats dictionaries, and does dump only once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM