在相当长的 Python 程序的一部分中,我有以下初始 JSON 对象:
{
"Topics": {
"Topic": [
{
"Topic Id": "",
"Topic Title": "A short title that describes this topic",
"Conversations": {
"Conversation": [
{
"Conversation Id": "",
"Conversation Title": "",
"Conversation Text": ""
}
]
}
}
]
}
}
我正在迭代一系列输入并创建初始条目,如下所示:
newtopic = {
"Topic Id": topicId,
"Topic Title": json_data.get("Topic Title", None),
"Conversations": json.dumps(Conversations[thisConversation])
}
这似乎有效(尽管没有“对话”标签),但我不知道如何附加到对话数组。
# None of these work
if topicId == currentTopic["Topic Id"]:
currentTopic["Conversations"].update(json.dumps(Conversations[thisConversation]))
if topicId == currentTopic["Topic Id"]:
currentTopic["Conversations"].append(json.dumps(Conversations[thisConversation]))
if topicId == currentTopic["Topic Id"]:
currentTopic["Conversations"].extend(json.dumps(Conversations[thisConversation]))
我得到同样的错误:AttributeError:'str'对象没有属性'append' - 但'append'是我尝试的任何内容(例如扩展,更新)。
对话列表是根据远程 URL 调用动态生成的,我需要通过类似的调用发送主题列表结果。为此,我希望尽可能避免自定义 Python 类。
json.dumps 调用返回在 Conversation 属性下找到的 JSON 字符串。创建后,我尝试将其他 JSON 字符串附加到 Conditions 元素。
有演员阵容或者我应该做的事情吗?
当提出这样的问题时,您应该包含允许人们实际重现您所看到的问题的代码。目前这个问题需要我们进行大量猜测。更重要的是,因为您似乎误解了如何在 Python 中处理 JSON 的几个重要部分。
没关系,你来这里是为了学习,但你不能指望人们凭直觉理解你的代码。这是一个尝试:
import json
initial_json_text = """
{
"Topics": {
"Topic": [
{
"Topic Id": "",
"Topic Title": "A short title that describes this topic",
"Conversations": {
"Conversation": [
{
"Conversation Id": "",
"Conversation Title": "",
"Conversation Text": ""
}
]
}
}
]
}
}
"""
# this loads the object you probable have, which is a `dict` in Python
initial_json_object = json.loads(initial_json_text)
# getting the first topic, you apparently assigned some topic to json_data
json_data = initial_json_object["Topics"]["Topic"][0]
# you have *some* topic id - note that you should consider renaming this topic_id
topicId = json_data["Topic Id"]
# you reference some `Coversations` - the name suggests a class due to the capital
# but from the context it seems to be the conversations of some topic
Conversations = json_data["Conversations"]
# again, it's unclear where you get this from
thisConversation = 'Conversation'
# how you say you create a new topic
newtopic = {
# the topic is assigned the topicId, presumable a string
"Topic Id": topicId,
# the title is assigned the title from json_data, presumably another topic
"Topic Title": json_data.get("Topic Title", None),
# here is your issue - json.dumps turns a Python object into a JSON string
# so, you're assigning a string to the Conversations key
"Conversations": json.dumps(Conversations[thisConversation])
}
# what you probably wanted
newtopic = {
# the topic is assigned the topicId, presumable a string
"Topic Id": topicId,
# the title is assigned the title from json_data, presumably another topic
"Topic Title": json_data.get("Topic Title", None),
# here is your issue - json.dumps turns a Python object into a JSON string
# so, you're assigning a string to the Conversations key
"Conversations": Conversations[thisConversation]
}
# now this will add the conversation a second time, without error
newtopic["Conversations"].append(Conversations[thisConversation][0])
# you only want to use `.dumps()` when you need the JSON object represented
# as a string, for example when writing to a file
# for example, to add the topic to the original data, and write the result:
initial_json_object["Topics"]["New Topic"] = newtopic
result_json_text = json.dumps(newtopic)
# Note that you could print json_data as well, but that's because Python knows
# how to represent a `dict` as a string, if you're writing it to a file, you
# may want to have the string representation of the JSON object before writing
print(result_json_text)
请注意,您的数据结构有几个奇怪的特征,这可能是错误。
首先,您有
"Topics"
,它是一本由 "Topic"
等字符串索引的字典,但是字典中的每个主题都有一个 "Topic Id"
- 这可能只是字典中键的重复项?
类似地,您有
"Conversations"
这是一本字典,它似乎以 "Conversation"
之类的字符串作为键,但这种“对话”的实际值似乎是实际对话的 list ,带有单独的标识符。您是否打算将 "Conversations"
制作为一个列表,而花括号是错误的吗?
您调用
.dumps()
的次数似乎也远远超过了需要的次数,也许您不太明白它的作用 - 但这是您直接遇到的错误的核心,尽管您所做的选择可能会出现其他问题在文档结构中。
这样的事情会更有意义:
import json
initial_json_text = """
{
"Topics": {
"Topic 1": {
"Topic Title": "A short title that describes this topic",
"Conversations": {
"Conversation": {
"Conversation Title": "",
"Conversation Text": ""
},
"Another Conversation": {
"Conversation Title": "",
"Conversation Text": ""
}
}
}
}
}
"""
initial_json_object = json.loads(initial_json_text)
# "Topic 1" is the key for the first topic, and serves as the ID
topic = initial_json_object["Topics"]["Topic 1"]