【问题标题】:Printing each item of array in JSON format以 JSON 格式打印数组的每一项
【发布时间】:2017-03-08 23:22:14
【问题描述】:

我对 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 的列表。我知道我需要使用循环来执行此操作,但我对它们不是很熟悉。任何人都可以帮忙吗?谢谢。

【问题讨论】:

标签: python arrays json


【解决方案1】:

要对 JSON 进行编码,可以导入 JSON 模块并使用 dump 方法,而要对 JSON 进行解码,可以使用 loading 方法,例如:

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

【讨论】:

  • 很好,作为后续:假设用户被提示通过 raw_input 输入名称,然后这些名称存储在一个数组中。有没有办法构建一个循环来遍历这些名称中的每一个,然后在该 JSON 对象中将它们分别打印出来?例如,假设用户输入“Steve, John, Ted”。有没有办法让循环遍历这些名称并打印出 {"name": "Steve", "user_id": 1, "comment": "this is a comment"}, {"name": "John" ,“user_id”:1,“comment”:“这是一条评论”},{“name”:“Ted”,“user_id”:1,“comment”:“这是一条评论”}。抱歉,如果这已经显示了
  • 这是你想要实现的@user7681184,我使用输入,因为我正在使用 python 3,因为 raw_input 在 python 3 中不再使用
  • 谢谢克里斯,这很有道理。
猜你喜欢
  • 2016-10-08
  • 2020-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-23
  • 1970-01-01
相关资源
最近更新 更多