0

Is there any plugin or function that converts multi-dimensional JSON like this:

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

To array in this format

[ {"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") ] 

Or do I need to write it at my own? Forgive me if I am wrong but when jQuery makes ajax call input JSON has to be converted to data in format above?

I am trying to create function/plugin that creates form with hidden fields to be sent into <iframe>

So basically function like this but that allows multi-dimensional params

11
  • May be a duplicate of stackoverflow.com/questions/19098797/… Commented Oct 2, 2015 at 8:30
  • Shouldn't "hello[arr][]" : "a" be "hello[arr][1]" : "a" and so, otherwise the values will be overridden because they all are having same key Commented Oct 2, 2015 at 8:31
  • @Tushar I copied it from firebug console, that's how data is sent to my server and PHP parses it correctly Commented Oct 2, 2015 at 8:33
  • @Jaay no, different output Commented Oct 2, 2015 at 8:34
  • @Peter the output you have there is not valid JSON; it doesn't have commas after each mapping. Can you print the result that is received server-side? Commented Oct 2, 2015 at 8:35

1 Answer 1

0

Ok I made my custom function:

$.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; } 

Demo: http://jsfiddle.net/9wL9zz8L/

And in the result I can create my form with hidden data that can be submitted to <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(); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.