简体   繁体   English

如何从顶部开始解析json字符串?

[英]How to parse json string starting from the top?

I have a json API that has many optional fields. 我有一个json API,其中包含许多可选字段。 When I receive this object I need to parse it and add the data to a database. 当我收到这个对象时,我需要解析它并将数据添加到数据库中。 JSON.parser() seems to parse the inner most data first which is a waste. JSON.parser()似乎首先解析了最里面的数据,这很浪费。 I need to start parsing from the top most level first. 我需要首先从最高级别开始解析。

Will I need to make a custom string parser or is one available? 我需要做一个自定义的字符串解析器吗?

Example API: 示例API:

"AddRequest" : {
    "OptionalId" : "",
    "OptionalType" : {
        "Status" : "taken",
        "DateStart" : "21/05/2013",
        "DateEnd" : "21/06/2013",
        "Summary" : "It was really good"
    },
    "OptionalHotels" : [
        {
            "HotelId" : "1",
            "CheckIn" : "21/05/2013", 
            "CheckOut" : "21/06/2013", 
            "Name" : "Hotel Name", 
            "Latitude" : "", 
            "Longitude" : "",
            "City" : "Toronto"
        },
        ... 
    ],
    ...
}

The code: 编码:

var jsonObject = JSON.parse(data , 
    function(k, v) {
        console.log(k + ':' + v);
    }
);

The second argument to JSON.parse is a function to transform the data. JSON.parse的第二个参数是转换数据的函数。

If you just want to access it, then parse it normally and then access the properties you care about from the return value. 如果只想访问它,则可以正常解析它,然后从返回值访问您关心的属性。

var javaScriptObject = JSON.parse(data);
console.log(javaScriptObject.whateverYouWantFirst);

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

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