首页 > 解决方案 > 替换json中文本的最佳方法是什么?

问题描述

所以我有一堆JSON数据,它包含一些字段。例如:

[{
    "id": "XXX",
    "version": 1,
    "head": {
        "text": "Main title",
        "sub": {
            "value": "next"
        },
        "place": "secondary"
    },
    "body": [{
            "id": "XXX1",
            "info": "three little birds",
            "extended": {
                "spl": {
                    "text": "song",
                    "type": {
                        "value": "a"
                    }
                }
            }
        },
        {
            "id": "XXX2",
            "info": [
                "how are you?"
            ],
            "extended": {
                "spl": {
                    "text": "just",
                    "non-type": {
                        "value": "abc"
                    }
                }
            }
        }
    ]
}]
  1. 我想要做的是一种转换表(来自不同的 JSON 文件),如果一个字段的值为 'a' 将其替换为 'some other text..' 等。

  2. 我有JSON管道服务,所以我想这是进行更换的正确位置。

所以对于这个例子,我有JSON上述内容,在我的转换表中我有以下术语:

下一个:转发,歌曲:音乐,a:option1,just:来自等...

标签: javascriptjson

解决方案


您正在寻找的可以通过模板实现。用一些特定的标记替换变量部分,您可以从一些外部工具(例如perl或)中找到并替换这些标记sed

例如,你可以有这样的template.json东西:

...
"type": {
  "value": "@@VALUE@@"
}
...

然后,当您需要实际的 JSON 时,您可以通过中间脚本传递它,用实际数据替换这些模板。

cat template.json | sed -e 's/@@VALUE@@/my_value/' > target.json

或者,使用 Perl:

cat template.json | perl -pi -e 's:\@\@VALUE\@\@:my_value:' > target.json

推荐阅读