如何在一行中正确循环并打印json记录

问题描述 投票:0回答:1

下面的代码循环遍历记录并逐条垂直显示结果。

这就是我想要的

我需要在一行中打印此文本,例如。 Stackoverflow.com 是一个程序员问答网站

import os
import json
my_json = '["Stack", "over" , "flow", ".com", "is a ", "Programmers Question and Answering Site"]'
data = json.loads(my_json)

# for result in data.values():
for result in data:
    print(result)
# Display the result in a single line
python json
1个回答
0
投票

类似

json.loads('["a"]')
的东西只是将字符串(有效的 JSON)解释为条目列表..正如其他人在评论中指出的那样,然后您可以使用字符串的
.join()
方法将它们连接在一起(注意该方法实际上是来自您要加入的子字符串,而不是字符串集合的某个成员)

>>> import json
>>> json.loads('["a"]')
['a']
>>> ":".join(["one", "two", "three"])
'one:two:three'

在一起

>>> " ".join(json.loads(my_json))
'Stack over flow .com is a  Programmers Question and Answering Site'

并修复一些条目周围的不良间距

>>> print(" ".join(s.strip() for s in json.loads(my_json)))
Stack over flow .com is a Programmers Question and Answering Site
© www.soinside.com 2019 - 2024. All rights reserved.