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.

2
  • 1
    Possible duplicate of Safely turning a JSON string into an object Commented Mar 24, 2018 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. Commented Mar 24, 2018 at 23:03

2 Answers 2

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
  ])
})
Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.