Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 925917
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T19:35:50+00:00 2026-05-15T19:35:50+00:00

I would like to convert flat form data to recursive JSON data in python

  • 0

I would like to convert flat form data to recursive JSON data in python or javascript. This JSON data can later be interpreted by a template engine (google for tempest, it has django like syntax). There are plenty examples to convert flat data to recursive data, but the problem is it can’t be a dict or list only.

I tried to do it in many ways, but didn’t succeed yet. So after scratching my head for at least two weeks, I decided to ask a question here.

The formdata is like this (key names may be different):

formdata = [
    {"formname": "name", "formvalue": "Roel Kramer"},
    {"formname": "email", "formvalue": "blaat@blaat.nl"},
    {"formname": "paragraph-0.title", "formvalue": "test titel 1"},
    {"formname": "paragraph-0.body", "formvalue": "bla bla body 1"},
    {"formname": "paragraph-0.image-0.src", "formvalue": "src 1"},
    {"formname": "paragraph-0.image-1.src", "formvalue": "src 2"},
    {"formname": "paragraph-1.title", "formvalue": "test titel 2"},
    {"formname": "paragraph-1.body", "formvalue": "bla bla body 2"},
    {"formname": "paragraph-1.image-0.src", "formvalue": "src 3"},
    {"formname": "paragraph-1.image-1.src", "formvalue": "src 4"},
    {"formname": "paragraph-1.image-2.src", "formvalue": "src 5"},
    {"formname": "paragraph-2.title", "formvalue": "test titel 3"},
    {"formname": "paragraph-2.body", "formvalue": "bla bla body 3"},
    {"formname": "paragraph-2.image-0.src", "formvalue": "src 6"},
    {"formname": "paragraph-2.image-1.src", "formvalue": "src 7"},
]

I would like to convert it to this format:

{'paragraph':
    [
        {
        'image': [{'src': 'src 1'}, {'src': 'src 2'}],
        'body': 'body 2',
        'title': 'titel 2'
        },
        {
        'image': [{'src': 'src 3'}, {'src': 'src 4'}, {'src': 'src 5'}],
        'body': 'body 2',
        'title': 'titel 2'
        },
        {
        'image': [{'src': 'src 6'}, {'src': 'src 7'},
        'body': 'body 3',
        'title': 'titel 3'
        },
    ],
}

As you can see I mix dicts with lists, which makes it a bit harder. In my last attempt I got to the point where the script figures out where to add lists and where to add dicts. This results in this:

{'paragraph': [{'image': []}, {'image': []}, {'image': []}]}

But when I add data the result is not what I expected.

{
  "paragraph": [{
    "body": "bla bla body 1",
    "image": {
      "src": "src 7"
    },
    "title": "test titel 1"
  }, {
    "body": "bla bla body 2",
    "image": {
      "src": "src 5"
    },
    "title": "test titel 2"
  }, {
    "body": "bla bla body 3",
    "image": {
      "src": "src 3"
    },
    "title": "test titel 3"
  }, {
    "image": {
      "src": "src 6"
    }
  }],
  "name": "Roel Kramer",
  "email": "contact@roelkramer.nl"
}

The total script can be seen at github gist. I know it can be much cleaner, but I will refactor it when it works.

What am I doing wrong? Am I totally missing something?
Thanks a lot!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T19:35:51+00:00Added an answer on May 15, 2026 at 7:35 pm

    Well, if you know the format will be consistent then something like this will work:

    def add_data(node, name, value):
        if '-' not in name:
            node[name] = value
        else:
            key = name[:name.index('-')]
            node_index = int(name[len(key) + 1:name.index('.')])
            node.setdefault(key, [])
            if node_index >= len(node[key]):
                node[key].append({})
            add_data(node[key][node_index],
                     name[name.index('.') + 1:],
                     value)
    

    Then to use it, just do something like this:

    root_node = {}
    for data in formdata:
        add_data(root_node, data['formname'], data['formvalue'])
    

    The function makes the following assumptions:

    1. The – character is used to specify which node of a particular node type, and is followed
      by a number.
    2. The . character separates nodes in the tree, and always follows the index number.
    3. The form data will always go in order. (paragraph-0, paragraph-1, paragraph-2) instead of (paragraph-1, paragraph-0, paragraph-3).

    So, here’s the code with comments explaining it:

    def add_data(node, name, value):
        # We're at a parent node (ex: paragraph-0), so we need to drill down until
        # we find a leaf node
        if '-' in name:
            key = name[:name.index('-')]
            node_index = int(name[len(key) + 1:name.index('.')])
    
            # Initialize the parent node if needed by giving it a dict to store it's
            # information nodes
            node.setdefault(key, [])
            if node_index >= len(node[key]):
                node[key].append({})
    
            # Drill down the tree by calling this function again, making this
            # parent node the root
            add_data(node[key][node_index],
                     name[name.index('.') + 1:],
                     value)
    
        # We're at a leaf node, so just add it to the parent node's information
        # ex:  The first formdata item would make the root_node dict look like
        # { 'name': 'Roel Kramer' }
        else:
            node[name] = value
    

    Here’s a working example: http://pastebin.com/wpMPXs1r

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 530k
  • Answers 530k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer I think this is another one of those examples where… May 16, 2026 at 11:27 pm
  • Editorial Team
    Editorial Team added an answer find-file does not make distinctions between frames, you could launch… May 16, 2026 at 11:27 pm
  • Editorial Team
    Editorial Team added an answer You'd like to put the bean in the view scope… May 16, 2026 at 11:27 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Related Questions

I would like to convert a string into a node. I have a method
I would like to know what is the easiest way to convert an int
I have a standard Rails application. When a Tip is created, I would like
here is my xml: <record> <id>12342</id> <name>xx</name> <blah1>asdfas</blah1> <blah2>asdfas</blah2> ..... </record> I would like
Using This code: I am tring to fill the page with the data and
I have the Lat/Long value of New York City, NY; 40.7560540,-73.9869510 and a flat
Does anyone know of any tools to provide simple, fast queries of flat files
Item in the recordset rstImportData(Flat Size) is = Null With that, given the following
I have an Excel source going into an OLE DB destination. I'm inserting data
I am new to PHP and cannot figure out the best method to convert

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.