一尘不染

替换JSON对象中的值

json

我的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}  ]

我要替换"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>

谢谢,


阅读 981

收藏
2020-07-27

共1个答案

一尘不染

您需要使替换全局:

var old = JSON.stringify(data).replace(/null/g, '"#"'); //convert to JSON string
var newArray = JSON.parse(old); //convert back to array

这样,它将继续替换null直到到达结尾

正则表达式文档:

https://developer.mozilla.org/zh-
CN/docs/Web/JavaScript/Reference/Global_Objects/RegExp

另外,请注意,您应避免将其new用作变量名,因为它是javascript中的保留字,并且大多数浏览器都不允许您使用它

2020-07-27