Home > database >  Convert Specific String to JSON Object
Convert Specific String to JSON Object

Time:12-29

const test ="[{contactId=2525, additionDetail=samle}]";

I need to convert this string to a JSON object. It will dynamically load like this string. I need to particular string to convert to a JSON object.

JSON.parse(test) command not working for this. I attached the error here.

enter image description here

Thank You

CodePudding user response:

You should note that Json means javascript object notation, so you need to create a JavaScript object to get started:

const test ="[{contactId=2525, additionDetail=samle}]";
let obj = Object.create(null)

You can now define your variable as one of the object properties :

obj.test = test

Now we have a JavaScript object and we can convert it to json:

let convertedToJson = JSON.stringify(test);

CodePudding user response:

[{contactId=2525, additionDetail=samle}]

this is not a valid JSON-string, and it cannot be parsed by JSON.parse()

the correct JSON-string would be:

const test ='[{"contactId":2525, "additionDetail":"samle"}]';

CodePudding user response:

For that specific string, you'd have to parse it yourself.

const test = '[{contactId=2525, additionDetail=samle}]';
const obj = {};
test.split(/[{}]/)[1].split(/, /).forEach((elm) => {
  const entry = elm.split('=');
  obj[entry[0]] = entry[1];
});

What I am doing is splitting the string on the braces and selecting the second element (utilising regex) then splitting that on comma or space (again regex) then loop over the result and assign to an object. You can then JSON.stringify(obj) for the result.

  • Related