替换JSON对象中的值
我的data
apicontroller返回了以下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} ]
我要替换"parent":null
为"parent":'"#"'
我已经尝试了下面的代码,但它仅代替的第一次出现"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>
谢谢,
回答:
您需要使替换全局:
var old = JSON.stringify(data).replace(/null/g, '"#"'); //convert to JSON stringvar newArray = JSON.parse(old); //convert back to array
这样,它将继续替换null直到到达结尾
正则表达式文档:
https://developer.mozilla.org/zh-
CN/docs/Web/JavaScript/Reference/Global_Objects/RegExp
以上是 替换JSON对象中的值 的全部内容, 来源链接: utcz.com/qa/431461.html