Home > Net >  Convert String to Object gives error due to double quotes at start and end
Convert String to Object gives error due to double quotes at start and end

Time:04-10

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

CodePudding user response:

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"
    }
  }
}

CodePudding user response:

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));
  • Related