Home > Mobile >  convert string to object from html input element
convert string to object from html input element

Time:09-22

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? like just removing the outer quotation marks?

CodePudding user response:

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>

CodePudding user response:

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)

  • Related