我正在做一个api调用,该调用导致对象放在方括号内。

码:

        request.get(options, function(error, response, body) {

            var JSONdata = (JSON.stringify(body));
            var trip = JSON.parse(JSONdata).results;
            console.log(trip);

    });


日志:

[ { id: 'T_ec926d18c46e39d9',
url: 'https://api.automatic.com/trip/T_ec926d18c46e39d9/',
driver: 'https://api.automatic.com/user/U_0c1ee2ddcfea14be/',
vehicle: 'https://api.automatic.com/vehicle/C_7e050c914a0d2b97/',
duration_s: 447.3,
distance_m: 3375.3,
started_at: '2017-10-31T02:11:58.607000Z',
ended_at: '2017-10-31T02:19:25.918000Z',
start_timezone: 'America/Toronto',
end_timezone: 'America/Toronto',
tags: [],
idling_time_s: 0,
user: 'https://api.automatic.com/user/U_0c1ee2ddcfea14be/' } ]


我正在尝试从该对象中解析“ distance_m”,但将其转换为字符串会导致:

    [{"id":"T_ec926d18c46e39d9","url":"https://api.automatic.com        /trip/T_ec926d18c46e39d9/","driver":"https://api.automatic.com/user/U_0c1ee2ddcfea14be/","vehicle":"https://api.automatic.com/vehicle/C_7e050c914a0d2b97/","duration_s":447.3,"distance_m":3375.3,"started_at":"2017-10-31T02:11:58.607000Z","ended_at":"2017-10-31T02:19:25.918000Z","start_timezone":"America/Toronto","end_timezone":"America/Toronto","tags":[],"idling_time_s":0,"user":"https://api.automatic.com/user/U_0c1ee2ddcfea14be/"}]


我无法解析任何内容(由于方括号,我想假设)

我试过用正则表达式替换方括号,但这也不起作用(如此处所示:How to remove square brackets in string using regex?

如何将“ distance_m”值提取到变量中?

最佳答案

方括号代表一个数组-如果只需要第一项,则可以非常简单地访问它:

trip[0].distance_m

关于javascript - 如何从方括号内的对象解析字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47062806/

10-16 00:04