简体   繁体   English

如何从方括号内的对象解析字符串

[英]How can I parse a string from an object inside square brackets

I'm doing an api call that is resulting in an object inside square brackets. 我正在做一个api调用,该调用导致对象放在方括号内。

Code: 码:

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

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

    });

Log: 日志:

[ { 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/' } ]

I'm trying to parse the "distance_m" out of this object but converting it to a string results in: 我正在尝试从该对象中解析“ 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/"}]

which I cannot parse anything out of (I'm assuming because of the square brackets) 我无法解析任何内容(由于方括号,我想假设)

I've tried replacing the square brackets with regex but that does not work either (as showed here: How to remove square brackets in string using regex? ) 我试过用正则表达式替换方括号,但也不起作用(如此处所示: 如何使用正则表达式删除字符串中的方括号?

How can I extract the "distance_m" value to a variable? 如何将“ distance_m”值提取到变量中?

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

trip[0].distance_m

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

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