Javascript 替换 JSON 对象中的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28639345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replacing values in JSON object
提问by Erwin1
I have the following JSON object datareturned from my apicontroller :
我的dataapicontroller 返回了以下 JSON 对象:
> [ {"id":2,"text":"PROGRAMME","parent":null},
> {"id":3,"text":"STAGE","parent":2},
> {"id":4,"text":"INFRA","parent":2},
> {"id":5,"text":"SYSTEM","parent":3},
> {"id":6,"text":"STOCK","parent":3}, {"id":7,"text":"DPT","parent":3},
> {"id":9,"text":"EXTERNAL","parent":null} ]
I want to replace "parent":nullwith "parent":'"#"'
我想替换"parent":null为"parent":'"#"'
I have tried the code below, but it is only replacing the first occurrence of "parent":null. How can I replace all "parent":nullentries?
我已经尝试了下面的代码,但它只是替换了第一次出现的"parent":null. 如何替换所有"parent":null条目?
<script>
$(document).ready(function () {
$.ajax({
url: "http://localhost:37994/api/EPStructures2/",
type: "Get",
success: function (data) {
var old = JSON.stringify(data).replace(null, "'#'"); //convert to JSON string
var new = JSON.parse(old); //convert back to array
},
error: function (msg) { alert(msg); }
});
});
</script>
Thanks,
谢谢,
回答by Jonathan Crowe
You need to make the replace global:
您需要将替换设为全局:
var old = JSON.stringify(data).replace(/null/g, '"#"'); //convert to JSON string
var newArray = JSON.parse(old); //convert back to array
This way it will continue to replace nulls until it reaches the end
这样它将继续替换空值,直到它结束
Regex docs:
正则表达式文档:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
Also, as a side note, you should avoid using newas a variable name as it is a reserved word in javascript and most browsers will not allow you to use it
另外,作为旁注,您应该避免new用作变量名,因为它是 javascript 中的保留字,大多数浏览器不允许您使用它
回答by nrabinowitz
@JonathanCrowe's answer is correct for regex, but is that the right choice here? Particularly if you have many items, you'd be much better off modifying the parsed object, rather than running it through JSON.stringifyfor a regex solution:
@JonathanCrowe 的答案对于正则表达式是正确的,但这是正确的选择吗?特别是如果你有很多项目,你最好修改解析的对象,而不是运行它JSON.stringify以获得正则表达式解决方案:
data.forEach(function(record) {
if (record.parent === null) {
record.parent = "#";
}
});
In addition to being faster, this won't accidentally replace other nulls you want to keep, or mess up a record like { text: "Denullification Program"}.
除了速度更快之外,这不会意外替换您想要保留的其他空值,或弄乱像{ text: "Denullification Program"}.
回答by MarvinJWendt
A simple one liner would be:
一个简单的衬里是:
let json = JSON.parse(JSON.stringify(data).replace(/null/g, '"#"'));

