Search code examples
javascriptpythonjsondictionaryturbogears2

python unpack a dict from json


I've been searching around, but I cannot find an answer, my guess is that my question is not defined very well, so i hope to get some guidance

I'm using turbogears2.2 I'm sending from the client view a JavaScript object through $.post(), On the server I receive this object (as kw):

{'phones[1][surname]': u'sym', 'phones[2][name]': u'', 'phones[1][phone]': u'5498498', 'phones[0][phone]': u'0564', 'phones[1][name]': u'jhon', 'phones[0][surname]': u'cat', 'phones[2][phone]': u'', 'phones[0][name]': u'bob'}

I'm sending a data from a table with 3 columns

On my server I'm trying to separate the data for each row, but I'm a bit lost here. how can I split that dict into different rows of data?

Doing

import json
json.loads(str(kw))

Fails

{ValueError}: Expecting property name: line 1 column 2 (char 1)

How can I convert that dict/object to a nested dictionary (or something else)? Thanks


Solution

  • Thanks for the help Martijn Pieters , I thought I was posting JSON, but i wasn't.

    You didn't post JSON; you posted application/x-www-form-urlencoded data that jQuery formatted for the PHP array feature. – Martijn Pieters

    Here is my JavaScript, I'm trying out HandsOnTable (jQuery data grid editor)

    $("#sendToServer").click(function(){
            var tableData = $("#myTable").data('handsontable');
            $.post(
                URL,
                {phones:tableData.getData()},
                function(data){
                    console.log(data)
                }
            )
        })
    

    And that wasn't JSON, even though I thought it was

    Anyway, simple fix:

    Client side (JavaScript):

    var tableData = $("#myTable").data('handsontable');
    var jsonData = JSON.stringify(tableData.getData())
    ...
    $.post(URL,
         {phones:jsonData},
    ...
    )
    

    And now on the server side (Python):

    import json
    def getPhones(self,**kw):
            phones = json.loads(kw['phones'])
            ...
    

    And I have the data as a dict of rows, great

    Thanks for the guidance