简体   繁体   中英

Write a list objects in JSON using Python

I am trying to output the following JSON from my python (2.7) script:

[
  {
    "id": "1002-00001",
    "name": "Name 1"
  },
  {
    "id": "1002-00002",
    "display": "Name 2"
  },
]

What data structure in Python will output this when using json.dumps ? The outermost item is a python list, but what should be the type of items inside the list? It looks like a dictionary with no keys?

Hopefully this clarifies the notes in comments that are not clear for you. It's achieved by appending (in this case small) dictionaries into a list.

import json

#Added an extra entry with an integer type. Doesn't have to be string.
full_list = [['1002-00001', 'Name 1'],
            ['1002-00002', 'Name 2'],
            ['1002-00003', 2]]

output_list = []            
for item in full_list:
    sub_dict = {}
    sub_dict['id'] = item[0] # key-value pair defined
    sub_dict['name'] = item[1]
    output_list.append(sub_dict) # Just put the mini dictionary into a list

# See Python data structure
print output_list

# Specifically using json.dumps as requested in question.
# Automatically adds double quotes to strings for json formatting in printed 
# output but keeps ints (unquoted)
json_object = json.dumps(output_list)
print json_object 

# Writing to a file
with open('SO_jsonout.json', 'w') as outfile:
    json.dump(output_list, outfile)

# What I think you are confused about with the "keys" is achieved with an 
# outer dictionary (but isn't necessary to make a valid data structure, just
# one that you might be more used to seeing)
outer_dict = {}
outer_dict['so_called_missing_key'] = output_list
print outer_dict

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