Replacing values in JSON object

夙愿已清 提交于 2019-12-03 17:59:51

问题


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

I want to replace "parent":null with "parent":'"#"'

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>

Thanks,


回答1:


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

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




回答2:


@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.stringify for a regex solution:

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"}.



来源:https://stackoverflow.com/questions/28639345/replacing-values-in-json-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!