i have an object that is coming from the third party api. and it is in the form like this :
"{ "type": "object", "properties": { "hostUrl": {
"type": "string",
"description": "hostUrl", }, }, }"
due to the double quote in the start and the end i am getting error and json parse is also not being removed so kindly tell me how to remove this double quote which has wrapped my object inside it
try this
const jsonStr =
'"{ "type": "object", "properties": { "hostUrl": { "type": "string", "description": "hostUrl", }, }, }"';
var json = jsonStr
.substring(1, jsonStr.length - 1)
.replaceAll("},", "}")
.replaceAll(" ", "")
.replaceAll(",}", "}");
json
{
"type": "object",
"properties": {
"hostUrl": {
"type": "string",
"description": "hostUrl"
}
}
}
//Try this
let obj = {key:"{'name':'bhautik','age':24}"}
let a = obj.key
console.log(a) //it will log: "{'name':'bhautik','age':24}"
a = a.replaceAll('\'', "\"")
console.log(JSON.parse(a))
output:
[object Object] {
age: 24,
name: "bhautik"
}
if still not work then try this
let obj = {key:"{'name':'bhautik','age':24}"}
let a = obj.key
console.log(a) //it will log: "{'name':'bhautik','age':24}"
a = a.replaceAll('\'', "\"")
a = JSON.stringify(a)
console.log(JSON.parse(a))
output:
[object Object] {
age: 24,
name: "bhautik"
}
A JSON object stringified should always contain the object wrapped inside single quotes '. Yours' is wrapped inside a double quote ".
Since you are getting your JSON response in an unacceptable format and you cannot take that and parse directly add a single quote ' to the first and last of the response to make it valid.
That is,
if the response you're getting is
"{ "type": "object", "properties": { "hostUrl": { "type": "string", "description": "hostUrl" } } }"
adding single quote makes it
'"{ "type": "object", "properties": { "hostUrl": { "type": "string", "description": "hostUrl" } } }"'
Since now your object is a valid string, use the substring method and remove the wrongly placed double quotes to get a valid JSON stringified value.
Code as below:
let obj = '"{ "type": "object", "properties": {"hostUrl": { "type": "string", "description": "hostUrl" } }}"';
obj = obj.substring(1, obj.length-1);
console.log(JSON.parse(obj));