javascript 如何使用重复键动态生成 JSON 对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17063257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to generate a JSON object dynamically with duplicate keys?
提问by Razvan-Catalin Olaru
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 something like this:
我知道这听起来不可能,但我的老板告诉我,我必须使用 jQuery 通过 AJAX post 调用发送一个 JSON,它必须有重复的密钥。问题是,如果我写这样的东西:
$.post("someurl", {
"key1" : "value1",
"key2" : "value2",
"key2" : "value3",
"key2" : "value4",
"key3" : "value5"
});
, jQuery will send the request as
, jQuery 将请求发送为
someurl?key1=value1&key2=value4&key3=value5
all this because Javascript overwrites properties that have the same name. The JSON object is generated dynamically and I am NOT ALLOWED to use arrays in it. Can someone tell me how could I generate the JSON object dinamicaly and with duplicate keys?
这一切都是因为 Javascript 会覆盖具有相同名称的属性。JSON 对象是动态生成的,我不允许在其中使用数组。有人可以告诉我如何使用重复键生成 JSON 对象吗?
I would realy appreciate any help from you!
我真的很感激你的任何帮助!
回答by badp
From what I can see, {"a": "b", "a": "c"}
actually is validJSON according to RFC 4627.
据我所知,根据RFC 4627{"a": "b", "a": "c"}
实际上是有效的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 SHOULDbe unique.
对象结构被表示为一对大括号围绕零个或多个名称/值对(或成员)。名称是一个字符串。每个名称后面都有一个冒号,将名称与值分开。单个逗号将值与以下名称分开。对象内的名称应该是唯一的。
...where SHOULD means:
...其中应该意味着:
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.
3. 应该。这个词,或形容词“推荐”,表示在特定情况下可能存在合理的理由忽略特定项目,但在选择不同的课程之前必须理解并仔细权衡全部含义。
So yeah, basically you cando that, it is legal, but it's also a bad idea. Different JSON decoders will probably handle this situation differently and/or in undesiderable ways. Look at what the spec requires of parsers:
所以是的,基本上你可以这样做,这是合法的,但这也是一个坏主意。不同的 JSON 解码器可能会以不同的方式和/或以不受欢迎的方式处理这种情况。看看规范对解析器的要求:
A JSON parser transforms a JSON text into another representation. A JSON parser MUSTaccept all texts that conform to the JSON grammar. A JSON parser MAYaccept non-JSON forms or extensions.
An implementation mayset limits on the size of texts that it accepts. An implementation mayset limits on the maximum depth of nesting. An implementation mayset limits on the range of numbers. An implementation mayset limits on the length and character contents of strings.
JSON 解析器将 JSON 文本转换为另一种表示形式。JSON 解析器必须接受所有符合 JSON 语法的文本。JSON 解析器可以接受非 JSON 形式或扩展。
实现可能会对其接受的文本大小设置限制。一个实现可以对嵌套的最大深度设置限制。一个实现可以对数字范围设置限制。一个实现可以对字符串的长度和字符内容设置限制。
...but an implementation doesn't haveto handle situations like this sanely. For example:
...但实现不具有到三立处理这种情况。例如:
# 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"}
...and other implementations may legally give you (in Python notation):
...和其他实现可能合法地给你(在 Python 符号):
{"a": "b"}
[("a", "b"), ("a", "c")]
[("a", ["b", "c"])]
[]
42
"your JSON is bad and you should feel bad"
{"a": "b"}
[("a", "b"), ("a", "c")]
[("a", ["b", "c"])]
[]
42
"your JSON is bad and you should feel bad"
...or just good old nasal daemons. Literally the only illegal thing for a JSON parser to do here is raise an exception.
...或者只是很好的旧鼻守护进程。从字面上看,JSON 解析器在这里做的唯一非法事情就是引发异常。
The last thing you want to do in your production code is to rely on weird side cases. So the last thing you want to do is exercise your right to form nominally legal but practically useless JSON. If you want to do that, you'll have to do it by hand - build your own abstract syntax trees, your own parsers, your own generators, generators for anybody who might want to consume your data...
在生产代码中你最不想做的事情就是依赖奇怪的边际案例。因此,您最不想做的就是行使您的权利,以形成名义上合法但实际上无用的 JSON。如果你想这样做,你必须手工完成——构建你自己的抽象语法树、你自己的解析器、你自己的生成器、任何可能想要使用你的数据的人的生成器......
回答by lonesomeday
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.
具有重复键的 Javascript 对象不是 Javascript 对象。事实上,它只不过是你的想象。这是完全不可能的。
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
jQuery 将把它转换成 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?
这确实是做到这一点的唯一方法。* 您的代码无法生成有效的 JSON 有什么原因吗?
* Except for writing your own parser that handles invalid JSON. But that would be breathtakingly stupid.
* 除了编写自己的解析器来处理无效的 JSON。但这将是惊人的愚蠢。
回答by John Carlson
I would do it only if the JSON parser on the other side accepts it properly, without dropping anything. If you can show it dropping stuff, then you can look for another solution (like using an array, or generating the JSON by hand, or using a URL properly. You need better test cases first for your server.
只有当另一端的 JSON 解析器正确接受它时,我才会这样做,而不会丢弃任何东西。如果您可以向它展示丢弃的东西,那么您可以寻找其他解决方案(例如使用数组,或手动生成 JSON,或正确使用 URL。您首先需要为您的服务器提供更好的测试用例。
回答by Rodney P. Barbati
If you can't change the source at the source, then change the source into something you can at least work with...
如果你不能在源头上改变源头,那么把源头改成你至少可以使用的东西......
Parse the JSON into an Array of key value pairs (not into an object of key/value pairs).
将 JSON 解析为键值对数组(而不是键值对对象)。
You could do this easily if you have access to the JSON string, simply replace all "," with "},{" and wrap the result in "[" and "]".
如果您可以访问 JSON 字符串,则可以轻松完成此操作,只需将所有“,”替换为“},{”并将结果包装在“[”和“]”中。
You now have a valid JSON array of key/value pairs that is javascript legal.
您现在有一个有效的 JSON 键/值对数组,它是 javascript 合法的。