0

I have this JS/Jquery code that I'm attempting to modify:

new MyFormView({
        title: "Original"
        , collection: new MyFormSnippetsCollection([
          { "title" : "Form Name"
            , "fields": {
              "name" : {
                "label"   : "Form Name"
                , "type"  : "input"
                , "value" : "Form Name"
              }
            }
          }
        ])
      })

I want the JSON data to be inserted from a variable (rather than hard coded like above), so how do I insert the variable into the value of "MyFormSnippetsCollection"?

For example, I have the pre-formatted JSON in a string:

var jsondata = '{ "title" : "Form Name"
            , "fields": {
              "name" : {
                "label"   : "Form Name"
                , "type"  : "input"
                , "value" : "Form Name"
              }
            }
          }'

I'm looking for something like this (which didn't work):

new MyFormView({
        title: "Original"
        , collection: new MyFormSnippetsCollection([
          jsondata
        ])
      })

Or is not going to be that simple? Any suggestions appreciated.

BSUK
  • 692
  • 1
  • 12
  • 28
  • 1
    Possible duplicate of [Safely turning a JSON string into an object](https://stackoverflow.com/questions/45015/safely-turning-a-json-string-into-an-object) – pstanton Mar 24 '18 at 22:26
  • Apologies, I didn't know that the answer was to turn it into an object, hence me not being able to search for that answer. – BSUK Mar 24 '18 at 23:03

2 Answers2

2
JSON.parse

var jsondata = '{ "title" : "Form Name", "fields": { "name": { "label": "Form Name", "type": "input", "value": "Form Name" } } }';

var json = JSON.parse(jsondata);

document.getElementById("title").innerHTML = json.title;
<div id="title"></div>
Renari
  • 822
  • 7
  • 16
  • 32
2

As you said, if jsondata is a string, note that MyFormSnippetsCollection accepts an array with objects as children, not with strings as children. Convert jsondata to an object.

const jsondata = JSON.parse('{ "title" : "Form Name", "fields": {
  "name": {
    "label": "Form Name",
    "type": "input",
    "value": "Form Name"
  }
}
}');
new MyFormView({
  title: "Original",
  collection: new MyFormSnippetsCollection([
    jsondata
  ])
})
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320