BSUK
BSUK

Reputation: 745

Dynamically populate JSON array from variable value

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.

Upvotes: 0

Views: 940

Answers (2)

CertainPerformance
CertainPerformance

Reputation: 370699

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
  ])
})

Upvotes: 2

Renari
Renari

Reputation: 892

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>

Upvotes: 2

Related Questions