I have a textarea element which takes object types as an input
like
{
name: "root",
backlog: [
{name: "log#1"},
]
}
Accessing the data returns it as a string
Is there a simple way to convert the String to that specific javascript object without using regex filters? Just removing the outer quotation marks?
use json5 or Relaxed JSON library.
here is example using json5 library
let string = ` {
name: "root",
backlog: [
{name: "log#1"},
]
}`;
let object = JSON5.parse(string);
console.log(object)
<script src="https://unpkg.com/json5@^2.0.0/dist/index.min.js"></script>
To convert a string to a JSON, use: JSON.parse([the input]).
And, to convert it back to a string: JSON.stringify([the input]).
If i understand you correctly :
const string = '{ name: "root", backlog: [{name: "log#1"}]}'
const jsonStr = string.replace(/(\w+:)|(\w+ :)/g, function(matchedStr) {
return '"' + matchedStr.substring(0, matchedStr.length - 1) + '":';
});
const result = JSON.parse(jsonStr)
console.log(result)