Home > Enterprise >  Unable to parse json from api response
Unable to parse json from api response

Time:12-07

I am able to see the clear response in console.

{'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'}}}

but when i try to fetch the timestamp its printing undefined in console

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

CodePudding user response:

The problem seems to be that JSON.parse doesn't accept single qoutes. The best way to solve this is to change your backend implementation to something compliant with the JSON spec. If that isn't possible, you could do something like this, but note that this is quite a fragile solution.

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"
  • Related