javascript - 如何使用重复键动态生成 JSON 对象?

标签 javascript jquery ajax json

我知道这听起来不可能,但我的老板告诉我,我必须使用 jQuery 通过 AJAX post 调用发送一个 JSON,它必须有重复的键。问题是如果我这样写:

$.post("someurl", {
     "key1" : "value1",
     "key2" : "value2",
     "key2" : "value3",
     "key2" : "value4",
     "key3" : "value5"
});

,jQuery 将发送请求为

someurl?key1=value1&key2=value4&key3=value5

这一切都是因为 Javascript 会覆盖具有相同名称的属性。 JSON 对象是动态生成的,我不允许在其中使用数组。有人能告诉我如何动态生成 JSON 对象并使用重复键吗?

如果您能提供帮助,我将不胜感激!

最佳答案

据我所知,{"a": "b", "a": "c"} 根据 RFC 4627 实际上是有效 JSON .

An object structure is represented as a pair of curly brackets surrounding zero or more name/value pairs (or members). A name is a string. A single colon comes after each name, separating the name from the value. A single comma separates a value from a following name. The names within an object SHOULD be unique.

...应该意味着:

3. SHOULD. This word, or the adjective "RECOMMENDED", mean that there may exist valid reasons in particular circumstances to ignore a particular item, but the full implications must be understood and carefully weighed before choosing a different course.

所以是的,基本上您可以这样做,这是合法的,但这也是一个坏主意。不同的 JSON 解码器可能会以不同的方式和/或以不受欢迎的方式处理这种情况。查看规范对解析器的要求:

A JSON parser transforms a JSON text into another representation. A JSON parser MUST accept all texts that conform to the JSON grammar. A JSON parser MAY accept non-JSON forms or extensions.

An implementation may set limits on the size of texts that it accepts. An implementation may set limits on the maximum depth of nesting. An implementation may set limits on the range of numbers. An implementation may set limits on the length and character contents of strings.

...但是实现没有理智地处理这种情况。例如:

# Python 2.7
>>> import json
>>> json.JSONDecoder().decode('{"a": "b", "a": "c"}')
`{u'a': u'c'}`
# Chrome 32
> JSON.parse('{"a": "b", "a": "c"}')
Object {a: "c"}

...和其他实现可能合法地为您提供(以 Python 表示法):

  • {"a": "b"}
  • [("a", "b"), ("a", "c")]
  • [("a", ["b", "c"])]
  • []
  • 42
  • "your JSON is bad and you should feel bad"

...或者只是很好的旧nasal daemons .从字面上看,JSON 解析器在这里做的唯一非法事情就是引发异常。

您在生产代码中最不想做的事情就是依赖奇怪的边例。所以你最不想做的就是行使你的权利来形成名义上合法但实际上无用的 JSON。如果你想这样做,你将不得不手工完成 - 构建你自己的抽象语法树、你自己的解析器、你自己的生成器、为可能想要使用你的数据的任何人生成的生成器......

关于javascript - 如何使用重复键动态生成 JSON 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17063257/

相关文章:

javascript - 使用 React、Meteor 和 Simple Schema 创建动态单选按钮(使用 pup 样板)

javascript - $.parseJSON(响应);如果 resp 是数字它有效

javascript - 如何让变量取数值?

javascript - 获取select jquery的值

jquery - AJAX post 不发送数据到 laravel Controller

javascript - 如何在 .submit() 之后重新加载页面

javascript - 用冒号分隔的正则表达式编号

javascript - 未获取单击的 href 标签的索引值

javascript - 链接上的 e.preventDefault() 仍会加载页面

javascript - ajax调用WCF服务(跨域)