本文介绍了在JSON对象替换值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下的JSON对象数据
从我apicontroller返回:
I have the following JSON object data
returned from my apicontroller :
> [ {"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} ]
我要替换父:空
与父:#
我曾尝试下面的code,但它仅替换中第一次出现父:空
。我怎么能取代所有父:空
项
I have tried the code below, but it is only replacing the first occurrence of "parent":null
. How can I replace all "parent":null
entries?
<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 string
var newArray = JSON.parse(old); //convert back to array
此方式,将继续下去,直到到达结束更换空
This way it will continue to replace nulls until it reaches the end
正则表达式文档:
的
此外,作为一个侧面说明,你应该避免使用新
的,因为它是一个保留字的变量名JavaScript和大多数浏览器不会允许你使用它
Also, as a side note, you should avoid using new
as a variable name as it is a reserved word in javascript and most browsers will not allow you to use it
这篇关于在JSON对象替换值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!