简体   繁体   English

JSON 解析 Javascript 丢失 id 字段时出错

[英]Error in JSON parsing Javascript loosing id field

When I am parsing this string with JSON.parse().当我用 JSON.parse() 解析这个字符串时。 I get the objects with some of them containing id = null.我得到了其中一些包含 id = null 的对象。 I don't find any of the object that have id = null.我没有找到任何具有 id = null 的对象。 Is there really any issue?真的有什么问题吗?

                        console.log("TERRITORIES000: ");
                        console.log(territories);
                        territories = JSON.parse(territories);
                        console.log("TERRITORIES111: ");
                        console.log(territories);

And I see of the Territory with name "BC Paul (B.Baria, Akhaura)" contains id = null.我看到名为“BC Paul (B.Baria, Akhaura)”的领土包含 id = null。 But It's id is not null in the json string.但它的 id 在 json 字符串中不为空。 I am testing it in chrome browser.我正在 chrome 浏览器中测试它。 It weird.很奇怪。

[ {
  "name" : "MBKB, Sylhet (Metro, Biswanath, Kanaighat, Osmaninagar)",
  "area" : {
    "name" : "Sylhet",
    "region" : {
      "name" : "Sylhet",
      "id" : 3
    },
    "id" : 11
  },
  "id" : 36
}, {
  "name" : "MBKB (Sunamgonj)",
  "area" : {
    "name" : "Sylhet",
    "region" : {
      "name" : "Sylhet",
      "id" : 3
    },
    "id" : 11
  },
  "id" : 37
}, {
  "name" : "South Sylhet (Moulavi Bazar, Kulaura)",
  "area" : {
    "name" : "B.Baria",
    "region" : {
      "name" : "Sylhet",
      "id" : 3
    },
    "id" : 12
  },
  "id" : 38
}, {
  "name" : "B.C Paul (B.Baria, Akhaura)",
  "area" : {
    "name" : "B.Baria",
    "region" : {
      "name" : "Sylhet",
      "id" : 3
    },
    "id" : 12
  },
  "id" : 39
}, {
  "name" : "Sharif Store, (Habigonj)",
  "area" : {
    "name" : "B.Baria",
    "region" : {
      "name" : "Sylhet",
      "id" : 3
    },
    "id" : 12
  },
  "id" : 40
}, {
  "name" : "JR Corporation, (Bhairab)",
  "area" : {
    "name" : "Narshingdi",
    "region" : {
      "name" : "Sylhet",
      "id" : 3
    },
    "id" : 13
  },
  "id" : 41
}, {
  "name" : "JR Corporation, (Narsingdi)",
  "area" : {
    "name" : "Narshingdi",
    "region" : {
      "name" : "Sylhet",
      "id" : 3
    },
    "id" : 13
  },
  "id" : 42
}, {
  "name" : "Islam Traders, (Kishorgonj- 1, Kishorgonj- 2)",
  "area" : {
    "name" : "Narshingdi",
    "region" : {
      "name" : "Sylhet",
      "id" : 3
    },
    "id" : 13
  },
  "id" : 43
}, {
  "name" : "Noor  Son's (Mymensing, Fulpur, Bhaluka)",
  "area" : {
    "name" : "Mymensingh",
    "region" : {
      "name" : "Sylhet",
      "id" : 3
    },
    "id" : 14
  },
  "id" : 44
}, {
  "name" : "Amin & Co. (Sherpur, Jamalpur)",
  "area" : {
    "name" : "Mymensingh",
    "region" : {
      "name" : "Sylhet",
      "id" : 3
    },
    "id" : 14
  },
  "id" : 45
}, {
  "name" : "Shashi Mohan Roy (Netrokona)",
  "area" : {
    "name" : "Mymensingh",
    "region" : {
      "name" : "Sylhet",
      "id" : 3
    },
    "id" : 14
  },
  "id" : 46
} ]

This is the entire code这是整个代码

(function () {
    var Form = React.createClass({

        getDefaultProps: function () {
            return {
            };
        },
        getInitialState: function () {
            return {
                region: this.emptyRegion(),
                regions: []
            }
        },
        componentDidMount: function (e) {
            var $this = this;
            $.ajax({
                url: '/search-regions',
                method: 'get',
                cache: false,
                success: function (regions) {
                    regions = JSON.parse(regions);
                    $this.setState({regions: regions});

                    var region = regions.filter(function (region) {return region.id == $this.state.region.id})[0] || $this.emptyRegion();
                    region = JSON.parse(JSON.stringify(region));
                    region.areas = [];
                    region.area = $this.emptyArea();
                    $this.findRegion(region);

                }.bind($this),
                error: function (x) {
                    try {
                        alert(JSON.parse(x.responseText).message);
                    } catch (e) {
                        alert("Server Error: Please try again.");
                    }
                }.bind($this),
            });
        },
        onRegionChange: function (e) {
            var region = JSON.parse(JSON.stringify(this.state.region));
            region.id = e.target.value;
            this.findRegion(region);
        },
        onAreaChange: function (e) {
            var region = JSON.parse(JSON.stringify(this.state.region));
            region.area.id = e.target.value
            this.findRegion(region);
        },
        onTerritoryChange: function (e) {
            var region = JSON.parse(JSON.stringify(this.state.region));
            region.area.territory.id = e.target.value;
            this.findRegion(region);
        },
        render: function () {
            console.log("RENDERING: ");
            console.log(this.state.region);
            var modalCounter = 1;

            var region_ops = this.state.regions.map(function (region) {
                                 return (<option value={region.id} key={region.id}>{region.name}</option>);
                             });

            var area_ops = this.state.region.areas.map(function (area) {
                                 return (<option value={area.id} key={area.id}>{area.name}</option>);
                             });

            var territory_ops = this.state.region.area.territories.map(function (territory) {
                                 return (<option value={territory.id} key={territory.id}>{territory.name}</option>);
                             });

            return (
                <form>

                    <div className="row">
                        <div className="col-md-2">

                            <div className="form-group">

                                <select className="form-control"
                                value={this.state.region.id}
                                onChange={this.onRegionChange}
                                name="region">
                                    <option value="">Select Region</option>
                                    {region_ops}
                                </select>

                            </div>

                        </div>

                        <div className="col-md-2">

                            <div className="form-group">

                                <select className="form-control"
                                value={this.state.region.area.id}
                                onChange={this.onAreaChange}
                                name="area">
                                    <option value="">Select Area</option>
                                    {area_ops}
                                </select>

                            </div>

                        </div>

                        <div className="col-md-2">

                            <div className="form-group">

                                <select className="form-control"
                                value={this.state.region.area.territory.id}
                                onChange={this.onTerritoryChange}
                                name="territory">
                                    <option value="">Select Territory</option>
                                    {territory_ops}
                                </select>

                            </div>

                        </div>

                        <div className="col-md-3">

                        </div>

                        <div className="col-md-2">

                        </div>

                    </div>

                    <div className="row">

                        <div className="col-md-4">

                            <DateRange modalId={"filter-modal-" + modalCounter++}
                                       name="Date Range"
                                       value="~date_range~"
                                       modalTitle="Please Select Date Range"/>

                        </div>

                        <div id="" className="col-md-8">

                            <button id="" type="submit" className="btn btn-primary pull-right btn-form-footer"
                                    name="__action__" value="search">Search
                            </button>

                            <button id="" type="submit" className="btn btn-danger pull-right btn-form-footer"
                                    name="__action__" value="clear">Clear
                            </button>

                        </div>

                    </div>

                </form>
            );
        },

        findRegion: function (region) {
            var state = {region: JSON.parse(JSON.stringify(region))};
            console.log(region);
            var $this = this;
            if (!!region.id) {

                $.ajax({
                    url: '/search-territories?id=' + region.id,
                    method: "get",
                    success: function (territories) {
                            console.log("TERRITORIES000: ");
                            console.log(territories);
                            territories = JSON.parse(territories);
                            console.log("TERRITORIES111: ");
                            console.log(territories);

                        region.areas = territories.filter(function(t) {
                            return t.area.region.id == state.region.id;
                        }).map(function (t) {
                            return t.area;
                        });
                        var areas = {};
                        for(var x in region.areas) {
                            areas[region.areas[x].id] = region.areas[x];
                        }
                        var array = [];
                        for(var x in areas) {
                            array.push(areas[x]);
                        }
                        region.areas = array;

                        region.area = region.areas.filter(function(a) {return a.id == state.region.area.id})[0] || $this.emptyArea();
                        region.area = JSON.parse(JSON.stringify(region.area));
                        region.area.territories = [];
                        region.area.territory = $this.emptyTerritory();
                        if (!!region.area.id) {

                            console.log("TERRITORIES222: ");
                            console.log(territories);

                            region.area.territories = [];

                            for(var x in territories) {
                                if (territories[x].area.id == state.region.area.id) {
                                    region.area.territories.push(territories[x]);
                                }
                            }

                            console.log("ORIGINAL: ");
                            console.log(region.area.territories);

                            var trrs = {};
                            for(var x in region.area.territories) {
                                trrs[region.area.territories[x].id] = region.area.territories[x];
                            }
                            console.log("TERRR:");
                            console.log(trrs);
                            var array = []

                            for(var x in trrs) {
                                array.push(trrs[x]);
                            }
                            console.log("ARRAY:");
                            console.log(array)
                            region.area.territories = array;

                            region.area.territory = region.area.territories.filter(function (t) {return t.id = state.region.area.territory.id})[0] || $this.emptyTerritory();
                            region.area.territory = JSON.parse(JSON.stringify(region.area.territory));
                        }
                        console.log("SET STATE: ");
                        console.log(region);
                        $this.setState({region: region});
                    }.bind($this),
                    error: function (x) {
                        try {
                            alert(JSON.parse(x.responseText).message);
                        } catch (e) {
                            alert("Server Error: Please try again.");
                        }
                    }.bind($this),
                });

            }
        },

        emptyTerritory: function () {
                    return {
                        id: null,
                        name: "",
                    }
                },
        emptyArea: function () {
            return {
                id: null,
                name: "",
                territory: this.emptyTerritory(),
                territories: []
            }
        },
        emptyRegion: function () {
            return {
                id: null,
                name: "",
                area: this.emptyArea(),
                areas:[]
            }
        }
    });

    ReactDOM.render(<Form/>, document.getElementById("filters-div"));
})();

JSON libraries doesn't allow null objects, if you put a null object in your backend logic, the library won't add it to the JSON structure. JSON 库不允许空对象,如果您在后端逻辑中放置空对象,则库不会将其添加到 JSON 结构中。

Of course, all of this if you're generating the JSON.当然,如果您要生成 JSON,则所有这些都可以。

Java - ie: Java - 即:

JSONObject o = new JSONObject();
o.put("key",null);

If you call o.toString() the result will be:如果您调用 o.toString() 结果将是:

"{}"

You need to put a NULL object:您需要放置一个 NULL 对象:

JSONObject o = new JSONObject();
o.put("key",JSONObject.NULL);

If you call o.toString() the result will be:如果您调用 o.toString() 结果将是:

"{\"key\":null}"

If you're not generating the JSON, I can say that the JSON doesn't have any problem, when you're getting the id of an object, the result will be either the ID itself or undefined (null) depending if the id is present in the JSON structure.如果您没有生成 JSON,我可以说 JSON 没有任何问题,当您获取对象的id时,结果将是 ID 本身或未定义(空),具体取决于 id存在于 JSON 结构中。

Hope this helps!希望这可以帮助!

Hi finally I have found the answer.嗨,我终于找到了答案。 It is really weird.这真的很奇怪。 console.log(input) does not copy input if it is an nested object or array, not a primitive.如果输入是嵌套对象或数组,而不是原语,则 console.log(input) 不会复制输入。 If you change the nested object after calling console.log(), then it will be still reflected in the console window.如果在调用console.log() 之后更改了嵌套对象,那么它仍然会反映在控制台窗口中。 If you expand the nested object in the console window, you will see the latest state of the object, not the state where you console.log.如果在控制台窗口中展开嵌套对象,您将看到对象的最新状态,而不是您在 console.log 中的状态。 To see it simply run this code in the console of your browser.要查看它,只需在浏览器的控制台中运行此代码即可。

var x = {a: {b: {c: {}}}}
console.log(x)  //Don't look at the console at this time. Let the next line be executed.
x.a.b.c.name = "sohan"
//Then check the console. Expand the nested object. you will be surprised. The console is reflecting the latest state of the nested object.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM