我正在进行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”值提取到变量?
答案 0 :(得分:2)
方括号表示一个数组 - 如果您只需要第一个项目,则可以非常简单地访问它:
trip[0].distance_m