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!

3
  • 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 Commented Mar 17, 2014 at 15:43
  • How would a program know how to group the fields? Commented Mar 17, 2014 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. Commented Mar 17, 2014 at 16:05

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@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...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.