Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在json中,将所有键替换为减到下划线_Python_Json - Fatal编程技术网

Python 在json中,将所有键替换为减到下划线

Python 在json中,将所有键替换为减到下划线,python,json,Python,Json,我有一个json文件(事实上,超过数百个)。有时有些钥匙上有破折号 { “版本”:“0”, “id”:“xxxxxxxx-1395-088e-2704-07359f399de5”, “细节类型”:“测试”, “来源”:“aws”, ... } 我的目的是,查找任何键(有时是嵌套键),找出它并替换任何减号以加下划线 我可以用Python代码替换一个键,但是如果所有键的字符串中都有负号,那么如何搜索所有键呢 输出将是 { “版本”:“0”, “id”:“xxxxxxxx-1395-088e-270

我有一个json文件(事实上,超过数百个)。有时有些钥匙上有破折号

{
“版本”:“0”,
“id”:“xxxxxxxx-1395-088e-2704-07359f399de5”,
“细节类型”:“测试”,
“来源”:“aws”,
...
}
我的目的是,查找任何键(有时是嵌套键),找出它并替换任何减号以加下划线

我可以用Python代码替换一个键,但是如果所有键的字符串中都有负号,那么如何搜索所有键呢

输出将是

{
“版本”:“0”,
“id”:“xxxxxxxx-1395-088e-2704-07359f399de5”,
“细节类型”:“测试”,
“来源”:“aws”,
...
}
好了:

file_content = {
  "version": "0",
  "id": "xxxxxxxx-1395-088e-2704-07359f399de5",
  "detail-type": "test",
  "source": "aws"
}
for key in list(file_content.keys()):
    if not isinstance(key, str):
        continue
    value = file_content[key]
    del file_content[key]
    file_content[key.replace("-","_")] = value

print(file_content)

json读取和写入可以使用json模块的函数和来完成。

您可以添加所需的输出吗?更新,本示例中的输出,它只有一个键
detail key
,找到它并替换为
detail\u key
让我测试一下