打印JSON格式

打印JSON格式

问题描述:

我很新的Python的数组中的每个项目;过去我参加了一些初级课程,目前我已经编写了几个脚本来帮助我完成某些工作(主要涉及收集/解析数据)。我现在要做的是获取用户ID列表(从已放入数组的raw_input中获取),然后以JSON格式打印每个数字的列表。其结果必须是这个样子:打印JSON格式

{ 
    "user_id": "12345", 
    "name": "Bob", 
    "comment": "" 
} 

这是我到目前为止有:

script_users = map(int, raw_input("Please enter your user IDs, seperated by space with no comma: ").split()) 
final_users = list(set(script_users)) 

format = """ "name": "Bob", "comment": "" """ 

当时的想法是用我的格式变量打印出来使用,每个用户ID列表具体格式。我知道我需要使用循环来做到这一点,但我对他们不是很熟悉。谁能帮忙?谢谢。

+0

使用'json'模块以JSON格式打印Python数据。 – Barmar

+1

见https://docs.python.org/2/library/json.html – Barmar

为了编码JSON,你可以导入JSON模块,并使用转储方法和JSON解码可以使用负载的方法,例如:

import json 


json_data_encoding = json.dumps(
     {'user_id': 1, 'name': 'bob', 'comment': 'this is a comment'} 
) 

print(json_data_encoding) 
# output: {"name": "bob", "user_id": 1, "comment": "this is a comment"} 

json_data_decoding = json.loads(json_data_encoding) 
print(json_data_decoding['name']) 
# output: bob 

为了应对产生列表遵循代码如下,其中还展示了如何循环访问列表:

list_json_data_encoding = json.dumps([ 
    {'user_id': 1, 'name': 'bob', 'comment': 'this is a comment'}, 
    {'user_id': 2, 'name': 'tom', 'comment': 'this is another comment'} 
] 
) 

print(list_json_data_encoding) 
# output: [{"name": "bob", "user_id": 1, "comment": "this is a comment"}, {"name": "tom", "user_id": 2, "comment": "this is another comment"}] 

list_json_data_decoding = json.loads(list_json_data_encoding) 

for json_data_decoded in list_json_data_decoding: 
    print(json_data_decoded['name']) 
# output1: bob 
# output2: tom 

希望这会有所帮助。

这是你在找什么?

import json 


script_users = map(str, input("Please enter your user names, seperated by space with no comma: ").split()) 
users = list(set(script_users)) 

list_users = [] 
for user in users: 
    list_users.append({'user_id': 1, 'name': user, 'comment': 'this is a comment'}) 

json_user_list_encoding = json.dumps(list_users) 

print(json_user_list_encoding) 
# this will return a json list where user_id will always be 1 and comment will be 'this is a comment', 
# the name will change for every user inputed by a space 

json_user_list_decoding = json.loads(json_user_list_encoding) 

for json_user_decoded in json_user_list_decoding: 
    print(json_user_decoded['name']) 
# output: return the names as the where entered originally 
+0

大,作为后续行动:比方说,一个提示用户通过输入的raw_input名称,然后将这些名称存储在数组中。有没有办法构建一个循环来遍历每个这些名称,然后在每个JSON对象中输出它们?例如,假设用户输入“Steve,John,Ted”。是否有方法让循环遍历这些名称并打印{“name”:“Steve”,“user_id”:1,“comment”:“这是一条评论”},{“name”:“John” ,“user_id”:1,“comment”:“这是一条评论”},{“name”:“Ted”,“user_id”:1,“comment”:“这是一条评论”}。很抱歉,如果这已经显示 – user7681184

+0

这是你正在寻找实现@ user7681184什么,我使用的输入,因为我使用Python 3的raw_input作为被蟒蛇3 – Chris

+0

感谢克里斯内不再使用,这是有道理的。 – user7681184