1

I have a basic HTML form looking like this:

<html>
<form id="myform" action="something.cgi" method="post">
<select name="Container">
<option>container 1</option>
<option>container 2</option>
</select>
<input name="element1" type="text">
<!-- ... -->
</html>

My aim is the let the user do some configuration and save it to a config file where I can read it from another application. I'm looking for a method to create a JSON string like this

{
"Container 1": 
{
    "Group 1":
    {
        "element1": "value1",
        "element2": "value2"
    }
    "Group 2":
    {
        "element3": "value3",
        "element4": "value4"
    }
}
}

I read this POST data in JSON format but using the JSON.stringify method returns something like:

{
    "Container": "Container 1",
    "element1": "value1",
    "element2": "value2",
    "element3": "value3",
    "element4": "value4",
}

I'm wondering if there is a standard way of doing this? Thanks for help!

Community
  • 1
  • 1
inst27
  • 35
  • 6
  • 1
    can you expand the example to show `Container 2` and Group 1 and 2 definitions... ie what is the html that will generate the given json + a Container 2 also – Arun P Johny Mar 17 '14 at 15:43
  • How would a program know how to group the fields? – Aaron Digulla Mar 17 '14 at 15:47
  • @ArunPJohny The thing is that there is no definition of the groups. An html form consists of names and values. The grouping would have to be done by the code that generates the JSON string. – inst27 Mar 17 '14 at 16:05

1 Answers1

3

If you want to use javascript, you'll need to build it explicitly, i.e.:

var finalData = {
    Container:{
        'Group 1':{
            element1:'value1',
            element2:'value2'
        },
        'Group 2':{
            element3:'value3',
            element4:'value4'
        }
    }
};

JSON.stringify(finalData);

However if you need this to be dynamic, you need to get pretty tricky with Constructors and such. Since you're basing it off of an HTML form, I imagine the list of items is finite, and therefore an object literal setup like above should work for what you want.

Blazemonger
  • 90,923
  • 26
  • 142
  • 180
PlantTheIdea
  • 16,061
  • 5
  • 35
  • 40
  • @PlantTheldea You're right the base will be an html form with finite elements. If I have to be that explicit my thought is to post the form data "plain" and convert it to JSON in a CGI application. However I thought there would be a generic way... – inst27 Mar 17 '14 at 16:02