How to generate a JSON object dynamically with duplicate keys?

前端 未结 4 772
悲哀的现实
悲哀的现实 2020-12-01 21:34

I know this will sound impossible but my boss told me I MUST send a JSON over an AJAX post call with jQuery that MUST HAVE DUPLICATE KEYS. the problem is that if I write som

4条回答
  •  半阙折子戏
    2020-12-01 22:17

    A Javascript object with duplicate keys is not a Javascript object. In fact, it is no more than a figment of your imagination. It is totally impossible.

    The only way to do this is with an array:

    {
         "key1" : "value1",
         "key2" : ["value2", "value3", "value4"],
         "key3" : "value5"
    }
    

    jQuery will convert this into key1=value1&key2%5B%5D=value2&key2%5B%5D=value3&key2%5B%5D=value4&key3=value5

    This is genuinely the only way to do this.* Is there a reason why your code cannot generate valid JSON?

    * Except for writing your own parser that handles invalid JSON. But that would be breathtakingly stupid.

提交回复
热议问题