使用Python编写JSON中的对象列表

使用Python编写JSON中的对象列表,python,json,python-2.7,Python,Json,Python 2.7,我试图从python(2.7)脚本中输出以下JSON: 当使用json.dumps时,Python中的哪个数据结构将输出此数据? 最外层的项目是python列表,但列表中的项目类型应该是什么?它看起来像一本没有键的字典?希望这能澄清注释中对您来说不清楚的注释。它是通过在列表中添加(在本例中是小的)词典来实现的 import json #Added an extra entry with an integer type. Doesn't have to be string. full_list

我试图从python(2.7)脚本中输出以下JSON:

当使用
json.dumps
时,Python中的哪个数据结构将输出此数据?
最外层的项目是python列表,但列表中的项目类型应该是什么?它看起来像一本没有键的字典?

希望这能澄清注释中对您来说不清楚的注释。它是通过在列表中添加(在本例中是小的)词典来实现的

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

没有钥匙?那么“id”和“name”是什么呢?有一个字典列表
{“id”:idvalue,“name”:namevalue}
will dot这已经是一个非常有效的Python数据结构了。好吧,我很困惑。{“id”:idvalue,“name”:namevalue}的各个元素的类型是什么。其中有两个键值对。可能我盯着代码看得太久了。
repr(data).replace(“'”,““”)==json.dumps(data))
给了我真实的信息,因为您使用双引号编写了它,所以您编写的数据结构在这两种情况下都是有效的。
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