-1

I am trying to convert a JavaScript string into a workable JavaScript object without using the eval(). For example, convert a string like this:

beforeMagic="{{height: { type: String, default: \"auto\", realType: \"cssHeight\", required: false }, title: { type: String, required: true}}"

to

afterMagic= { height: { type: String, default: "auto", realType: "cssHeight", required: false }, title: { type: String, required: true } }

  • 3
    Where does the string come from? If there’s an option to make it valid JSON, then parsing it as JSON is trivial. How is the `type` property used? – Sebastian Simon Aug 18 '21 at 18:18
  • 2
    What is `type: String` supposed to mean? `String` is not a valid literal, it would need to be quoted. – Barmar Aug 18 '21 at 18:19
  • Without quotes, it's a variable (it's the built-in String class). Do you want the value of the variable put into the object? – Barmar Aug 18 '21 at 18:20
  • You can use `eval()` to parse it, but this is dangerous if the source is not trusted. – Barmar Aug 18 '21 at 18:20
  • 3
    The short answer, ignoring invalid input (`{{` and `}}`), and overlooking the unquoted text, is https://stackoverflow.com/questions/45015/safely-turning-a-json-string-into-an-object – erik258 Aug 18 '21 at 18:21

1 Answers1

4

To Deserialize a JSON into a JavaScript object, here you can use a common method JSON.parse() method.

var obj = JSON.parse(your-string);
H.S
  • 124
  • 1
  • 7