如何用其他东西代替所有存在的价值

时间:2018-06-24 14:03:49

标签: python json replace

我想找到一种简单的方法来替换JSON文件中的值。

我正在寻找类似的东西

json_file.replace("-", "")

示例:

"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
            }

预期:

"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
            }

添加了样本以及我的期望。

2 个答案:

答案 0 :(得分:2)

使用str.replace

演示:

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)

根据评论进行编辑

with open(filename, "r") as infile:
    data = infile.read().replace("-", "")

with open(filename, "w") as outfile:
    outfile.write(data)

答案 1 :(得分:1)

命令行工具是专为此类问题设计的。

例如,假设您要更改所有对象中所有键名(但仅键名)中的所有连字符, 不管嵌套有多深:

walk(if type == "object" then with_entries(.key |= gsub("-";"")) else . end)

如果您只想更改第一个连字符,则可以将gsub更改为sub

如果您的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之类的实用程序将派上用场。例如,如果JSON在文件中(例如input.json),并且如果上述jq程序在program.jq中,则可以按 如下:

jq -f program.jq input.json | sponge input.json