You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从JSON字符串中提取time字段值并通过console.log输出

解决方案

问题本质

你当前声明的json变量存储的是JSON格式的字符串,并非支持属性读取的JavaScript对象,因此直接使用json.time无法获取到对应字段值。

实现步骤

  • 调用JavaScript内置的JSON.parse()方法,将JSON格式字符串转换为可读取属性的普通JS对象
  • 从转换完成的对象中读取time属性,通过console.log输出即可

完整代码

let json = "{ \"time\":\"28-10-2021T23:20:28.402Z\", \"remoteIP\":\"192.168.1.1\", \"host\":\"www.serveurlardon.com\" }";
// 将JSON字符串转为JS对象
const jsonObj = JSON.parse(json);
// 输出time字段对应值
console.log(jsonObj.time);

可选优化(异常捕获)

如果JSON字符串存在格式错误,JSON.parse()会直接抛出异常,生产环境建议添加异常捕获逻辑:

let json = "{ \"time\":\"28-10-2021T23:20:28.402Z\", \"remoteIP\":\"192.168.1.1\", \"host\":\"www.serveurlardon.com\" }";
try {
  const jsonObj = JSON.parse(json);
  console.log(jsonObj.time);
} catch (error) {
  console.error('JSON字符串解析失败,请检查格式是否正确:', error);
}

内容的提问来源于stack exchange,提问作者Gamepigeek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 04:15:03