以JSON格式打印每个数组项

时间:2017-03-08 23:22:15

标签: python arrays json

我是Python的新手;我过去参加了几门初级课程,目前我已经将几个脚本放在一起帮助我完成某些工作(主要与收集/解析数据有关)。我现在要做的是获取用户ID列表(取自已放入数组的raw_input),然后以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的列表。我知道我需要使用一个循环来做这个,但我不是很熟悉它们。有人可以帮忙吗?谢谢。

1 个答案:

答案 0 :(得分:0)

要编码JSON,您可以导入JSON模块并使用dump方法并解码jSON,您可以使用loads方法,例如:

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