【问题标题】:Unable to parse json from api response无法从 api 响应解析 json
【发布时间】:2022-01-12 09:42:04
【问题描述】:

我可以在控制台中看到清晰的响应。

{'timestamp': '2021-12-07 09:54:01.195543', '操作参数': {'quality_control':'需要采取的行动','tool_status':'正在运行', 'message': {'Resurvey': {'Survey Environment': '流量高于 threshold', 'Recommended Action': '修改泵关闭顺序'}}}, “传感器数据”:{“位深度”:“772”,“倾角”:“37.83”,“方位角”: '299.86','gravity_toolface':'11.43','survey':{'survey_counter': '140', 'survey_time': '2021-12-07 09:54:01.195520'}, 'previous_survey': {'previous_survey_depth': '1111', 'previous_survey_time': '2021-12-07 09:54:01.195539'}}}

但是当我尝试获取 timestamp 时,它在控制台中的打印未定义

  console.log("timestamp", JSON.parse(JSON.stringify(jobDetails)).timestamp);

【问题讨论】:

  • 你为什么要stringify-ing jobDetails 变量?我怀疑如果你把它排除在外,它会很好用。
  • 我试过了,但它的打印在控制台中没有定义
  • 你能说明你是如何获取数据的吗
  • 我正在使用套接字。它会弄乱问题。唯一的问题是解析响应

标签: reactjs json parsing


【解决方案1】:

问题似乎是JSON.parse doesn't accept single qoutes。解决此问题的最佳方法是将后端实现更改为 compliant with the JSON spec。如果这不可能,您可以这样做,但请注意,这是一个非常脆弱的解决方案。

const jobListings = "{'timestamp': '2021-12-07 09:54:01.195543', 'Operating Parameters': {'quality_control': 'Action Needed', 'tool_status': 'running', 'message': {'Resurvey': {'Survey Environment': 'Flow higher than threshold', 'Recommended Action': 'Modify pumps shutoff sequence'}}}, 'Sensor Data': {'bit_depth': '772', 'inclination': '37.83', 'azimuth': '299.86', 'gravity_toolface': '11.43', 'survey': {'survey_counter': '140', 'survey_time': '2021-12-07 09:54:01.195520'}, 'previous_survey': {'previous_survey_depth': '1111', 'previous_survey_time': '2021-12-07 09:54:01.195539'}}}"
const jsonJobListings = jobListings.replace(/'/g, '"')
const objJobListings = JSON.parse(jsonJobListings)
console.log(objJobListings.timestamp) // "2021-12-07 09:54:01.195543"

【讨论】:

  • 再次感谢@cerebralFart
猜你喜欢
  • 2017-05-08
  • 1970-01-01
  • 2018-06-19
  • 2019-05-22
  • 2023-03-18
  • 1970-01-01
  • 2016-01-16
  • 1970-01-01
相关资源
最近更新 更多