如何将多维json转换为嵌套的POST字段

How to convert multi-dimensional json to nested POST fields

本文关键字:嵌套 POST 字段 转换 json      更新时间:2023-09-26

是否有像这样转换多维JSON的插件或函数:

{
    "hello" : {
        "foo" : "bar",
        "arr" : ["a", "b", "c"]
    },
    "another": {
        "go" : {
            "very" : {                
                "deep" : 1                
            }
        }
    }
}

以这种格式进行数组

[
    {"key" : "another[go][very][deep]", "value" : "1"),
    {"key" : "hello[arr][]", "value" :a"),
    {"key" : "hello[arr][]", "value" :b"),
    {"key" : "hello[arr][]", "value" :c"),
    {"key" : "hello[foo]", "value" :bar")
]

还是我需要自己写?如果我错了,请原谅我,但当jQuery使ajax调用输入JSON必须转换为上述格式的数据?

我试图创建函数/插件,创建表单与隐藏字段发送到<iframe>

基本上就是这样的函数但它允许多维参数

我创建了自定义函数:

$.postirify = function(obj) {
    var tmp = $.param(obj).split("&");
    console.log(tmp);
    var result = [];
    $.each(tmp, function(i, v) {
        var kv = v.split("=");        
        result.push({
            key: decodeURIComponent(kv[0]),
            value: decodeURIComponent(kv[1])
        });
    });
    return result;
}

演示:http://jsfiddle.net/9wL9zz8L/

在结果中,我可以创建包含可以提交给<iframe>的隐藏数据的表单

$.fn.hiddenForm = function(data) {        
    var $form = $(this);
    $form.html("");
    var p = $.postirify(data);
    $.each(p, function(i, kv){
        var $input = $('<input/>');
        $input.attr("type", "hidden");
        $input.attr("name", kv.key);
        $input.val(kv.value);
        $form.append($input);
    });
    return $form;
};
$('#my-form').hiddenForm($.postirify(my_data)).submit();