[英]How to replace all existence value with something else
I would like to find a simple way to replace values in a JSON file. 我想找到一种替换JSON文件中值的简单方法。
I am looking for something similar to: 我正在寻找类似的东西:
json_file.replace("-", "")
SAMPLE: 样品:
"scores": {
"count": 1,
"my-followings": 420,
"my-plain-tweets": 0,
"my-tweets-with-links": 1,
"my-tweets-with-image": 0,
"my-replies": 0,
"my-listed": 113,
"my-retweets": 0,
"my-statuses": 3653,
"my-followers": 8536,
"favourites": 0,
"my-tweets-with-video": 0,
"my-favourites": 7929,
"retweets": 0
}
EXPECTED: 预期:
"scores": {
"count": 1,
"myfollowings": 420,
"myplaintweets": 0,
"mytweetswithlinks": 1,
"mytweetswithimage": 0,
"myreplies": 0,
"mylisted": 113,
"myretweets": 0,
"mystatuses": 3653,
"myfollowers": 8536,
"favourites": 0,
"mytweetswithvideo": 0,
"myfavourites": 7929,
"retweets": 0
}
Added sample and what I expected. 添加了示例以及我的期望。
Using str.replace
使用str.replace
Demo: 演示:
import json
with open(filename, "r") as infile: #Read json
data = json.load(infile)
data = dict((k.replace("-", ""), v) for k, v in data["scores"].items()) #Remove "-"
with open(filename, "w") as outfile: #Write back to file
data = json.dump({"scores": data}, outfile)
Edit as per comment 根据评论编辑
with open(filename, "r") as infile:
data = infile.read().replace("-", "")
with open(filename, "w") as outfile:
outfile.write(data)
The command-line tool jq is designed for this type of problem. 命令行工具jq专为此类问题而设计。
For example, suppose you want to change ALL the hyphens in ALL the key names (but only key names) in ALL objects, no matter how deeply nested: 例如,假设您想更改ALL对象中所有键名(但仅键名)中的所有连字符,无论嵌套的深度如何:
walk(if type == "object" then with_entries(.key |= gsub("-";"")) else . end)
If you only wanted to change the FIRST hypen, you'd change the gsub
to sub
. 如果你只是想更改第一个连字符,你会改变gsub
到sub
。
In case your jq does not have walk/1
, you can include its definition, eg 如果您的jq没有walk/1
,则可以包含其定义,例如
# Apply f to composite entities recursively, and to atoms
def walk(f):
. as $in
| if type == "object" then
reduce keys_unsorted[] as $key
( {}; . + { ($key): ($in[$key] | walk(f)) } ) | f
elif type == "array" then map( walk(f) ) | f
else f
end;
walk(if type == "object" then with_entries(.key |= gsub("-";"")) else . end)
sponge
用sponge
调用 If you want to overwrite the input file, then a utility such as sponge
would come in handy. 如果您想覆盖输入文件,那么诸如sponge
的实用程序sponge
上用场。 For example, if the JSON is in a file, say input.json, and if the jq program as above is in program.jq, then you could proceed as follows: 例如,如果JSON在文件中,例如input.json,并且如果上述jq程序在program.jq中,则可以按以下步骤进行:
jq -f program.jq input.json | sponge input.json
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.