如何从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
相关产品推荐
相关产品推荐

