Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stringify JSON -> Python Server gets dict with key which is stringified string

var jsData = {
    id:         'E1',
    firstname:  'Peter',
    lastname:   'Funny',
    project: { id: 'P1' },
    activities: [
        { id: 'A1' },
        { id: 'A2' }
    ]};

var jsonData = JSON.stringify(jsData);


$('#click').click(function(){

    $.ajax({
        url: "test/",
        type: "POST",
        data: jsData,
        dataType: "json",
        success: function (data){
        console.log(data);
        },
        error:function(){$('#text').html('FATAL_ERROR')}

    })
})

This is the JS-Code and jsData should be send to the Server(Python). On the Server i get something like {'{id:'E1',firstname:'Peter',lastname:'Funny',project: { id: 'P1' },activities: [{ id: 'A1' },{ id: 'A2' }]};':''}

Is there a smart way to get the string 'inner dict' out of the 'outer dict' ?!

like image 604
ShuftY Avatar asked Dec 27 '22 04:12

ShuftY


1 Answers

Python has a built-in JSON parsing library. Adding import json provides basic JSON parsing functionality, which can be used as follows:

import json
personString = "{'{id:'E1',firstname:'Peter',... " # This would contain your JSON string
person = json.loads( personString ) # This will parse the string into a native Python dictionary, be sure to add some error handling should a parsing error occur

person['firstname'] # Yields 'Peter'
person['activities'] # Yields a list with the activities.

More information here: http://docs.python.org/2/library/json.html

like image 111
Stephan Heijl Avatar answered Jan 24 '23 17:01

Stephan Heijl