【发布时间】:2022-01-10 00:59:36
【问题描述】:
我知道这个问题之前已经被问过。我看了以下帖子:
Python replace values in unknown structure JSON file
How to find and replace a part of a value in json file
https://pretagteam.com/question/how-to-replace-a-value-in-json-file-using-python
How to find and replace a part of a value in json file(不知何故这就是我正在寻找的,但它不适合我的问题,因为链接不同并且全部存储在“最新”下)
还有更多的贡献,但是我仍然卡住了。
我有一个像这样的简单 JSON 结构:
{
"guild1": {
"latest": [
"link1",
"link2"
],
"channel": channel_here
},
"guild2": {
"latest": [
"link"
],
"channel": channel_here
}
}
我找到了一种方法来遍历条目并打印找到条件的列表,例如:
# searching for link 1
["link1", "link2", "link3"] # here link 1 for example is found in one of the list entries
["link5"] -> This for example does not match what I am looking for, I can ignore this
如果找到,我只想用另一个之前定义的值替换它(只是link1)。我试图遍历找到列表的keys,但无法.replace 它或其他东西。与我的搜索条件匹配的键被打印出来,但我不能用它做任何其他事情。是否可以如此简单地更改列表中的条目?
主要是我也得到了以下错误,我也查过但没有得到任何更明智的错误:
TypeError: string indices must be integers
这是我搜索列表结尾“条目”的方式:
if defined_link in data[searchloop]['latest']: # data is my JSON file, searchloop the for-loop
for key in data[searchloop]['latest']: # Get all the matching keys
if key == defined_link: # Get the key I am looking for
也许其他人可以在这里帮助我!
【问题讨论】:
-
您说您尝试并做了几件事,但您没有提供任何 Python 代码,除了用于字符串列表的两个文字 - 您能否提供代码示例,解释发生了什么以及你期望的结果是什么?
-
@Grismar 抱歉,正在编辑帖子。再看看!
-
我是否理解正确,您希望找到任何出现的
["link1", "link2", "link3"]并用其他东西替换它们?你想用什么来代替它们?你想让他们在一个和所有的“公会”中被替换吗? -
@Grismar 我已经能够使用这个提供的循环找到属于我的搜索条件的所有链接。我想用一个新链接替换这些找到的链接,为此我只是将
"https://www.google.de/"作为测试,但当然没有发生任何事情。如果在每个“公会”中找到,我想替换它。
标签: python json discord.py