如何使用 Python (Django) 将 x-www-form-urlencoded 转换为 json

问题描述

从 api 我收到 x-www-form-urlencoded 数据。

    import React from "react";
         import ReactDOM from "react-dom";
         import WebDaTarocks from "webdaTarocks";
     
         export class Pivot extends React.Component<WebDaTarocks.Params,any> {
         webdaTarocks: WebDaTarocks.Pivot;
         
         componentDidMount() {
            const tempProps : any = this.props;
            const pivotData = tempProps.pivotData;
            const columnsData : any[] = tempProps.columnsData;
     
            const tempColums = [];
            const tempKeys = [];
     
            columnsData.forEach(cd => {
                const tempLabelColumn = cd.title;
                tempColums.push(tempLabelColumn);
                tempKeys.push(cd.key);
            });
     
            this.webdaTarocks = new WebDaTarocks({
                toolbar: true,report: {
                    dataSource: {
                        data: pivotData
                    },slice: {
                        rows: tempKeys,expands: {
                            expandAll: true
                        },measures: [{
                            "uniqueName": "Price","aggregation": "sum","format": "currency"
                        },{
                            "uniqueName": "discount","format": "currency"
                        }],columns: tempColums,},options: {
                        "grid": {
                            "type": "flat"
                        },formats: [{
                        "name": "","thousandsSeparator": " ","decimalSeparator": ".","decimalPlaces": 2,"maxSymbols": 20,"currencySymbol": "","currencySymbolAlign": "left","nullValue": " ","infinityValue": "Infinity","divideByZerovalue": "Infinity"
                    }]
                },container: ReactDOM.findDOMNode(this)
            });
         }
     
         componentwillUnmount() {
            // console.log('componentwillUnmount this.webdaTarocks',this.webdaTarocks.dispose);
            if (this.webdaTarocks.dispose) {
                 // this code break the system
                // this.webdaTarocks.dispose();
            }
         }
         
         shouldComponentUpdate() {
            return false;
         }
     
           render() {`enter code here`
            return <div>Pivot</div>;
           }
         }
     
         export default Pivot;

当我尝试使用 data = 'leads%5Bstatus%5D%5B0%5D%5Bid%5D=29078079' urllib.parse.parse_qs 进行转换时 我有一个

这样的字典
urllib.parse.unquote

如何将其转换为普通的 json 或 dict ? 像这样

{
    "leads[status][0][id]": [
        "29078079"
    ]
}

解决方法

字符串解析正确。所以问题不在于如何获得“正常”的 dict,而是如何更改 dict 键:

dictionary = { "leads[status][0][id]": [ "29078079" ] }
dictionary['leads'] = dictionary.pop(list(dictionary)[0])

或者,您可以手动创建字典:

dictionary =  {data[:5]:[data.split('=')[-1]]}