javascript - 替换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"
}
}
}
}
]
}]
我想要做的是一种转换表(来自不同的 JSON 文件),如果一个字段的值为 'a' 将其替换为 'some other text..' 等。
我有
JSON
管道服务,所以我想这是进行更换的正确位置。
所以对于这个例子,我有JSON
上述内容,在我的转换表中我有以下术语:
下一个:转发,歌曲:音乐,a:option1,just:来自等...
解决方案
您正在寻找的可以通过模板实现。用一些特定的标记替换变量部分,您可以从一些外部工具(例如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
推荐阅读
- javascript - 为什么我的函数无意中执行了两次?
- image - 从 Tensorflow 中的图像张量中提取随机不重叠的补丁
- sql - 如何根据分数选择表格中的前5名学生
- asp.net-mvc - 在带有 EF Core 应用程序的简单 ASP.NET Core MVC 中使用 DTO 和 AutoMapper
- sql - 在 ms sql server 中获取特定数据库中的模式
- javascript - 在映射函数中使用 async await
- machine-learning - 实现骰子损失的正确方法是什么?sigmoid 还是 softmax?
- python - python子进程模块调用方法
- angular-material-7 - 如何根据ngx mat select search得到的值过滤mat表中的数据
- python - Pandas:按列和索引的条件选择行