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

时间:2022-11-23 08:59:20

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!

我真的很感激你的帮助!

4 个解决方案

#1


16  

From what I can see, {"a": "b", "a": "c"} actually is valid JSON according to RFC 4627.

从我所看到的,{“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.

对象结构表示为一对围绕0或更多名称/值对(或成员)的花括号。名称是字符串。每个名称后面都有一个冒号,将名称与值分开。一个逗号将值与下面的名称分隔开。对象中的名称应该是惟一的。

...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 can do 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 MUST accept all texts that conform to the JSON grammar. A JSON parser MAY accept non-JSON forms or extensions.

JSON解析器将JSON文本转换为另一种表示形式。JSON解析器必须接受符合JSON语法的所有文本。JSON解析器可以接受非JSON形式或扩展。

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.

实现可以对其接受的文本的大小设置限制。实现可以对嵌套的最大深度设置限制。实现可以对数字的范围设置限制。实现可以对字符串的长度和字符内容设置限制。

...but an implementation doesn't have to 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", "b"), ("a", "c")]
  • ((“a”、“b”)(“a”、“c”)]
  • [("a", ["b", "c"])]
  • ((“a”、“b”,“c”)))
  • []
  • []
  • 42
  • 42
  • "your JSON is bad and you should feel bad"
  • " JSON不好,你应该感觉不好"

...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。如果你想这样做,你必须手工去做——建立你自己的抽象语法树,你自己的解析器,你自己的生成器,为任何想要使用你的数据的人建立生成器……

#2


3  

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的解析器。但这将是惊人的愚蠢。

#3


0  

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)。首先,您需要更好的测试用例。

#4


0  

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字符串的访问权限,您可以轻松地做到这一点,只需将“all”、“”替换为“}、{”并将结果包装为“[”和“]”即可。

You now have a valid JSON array of key/value pairs that is javascript legal.

现在,您有了一个合法的JSON数组的键/值对。

#1


16  

From what I can see, {"a": "b", "a": "c"} actually is valid JSON according to RFC 4627.

从我所看到的,{“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.

对象结构表示为一对围绕0或更多名称/值对(或成员)的花括号。名称是字符串。每个名称后面都有一个冒号,将名称与值分开。一个逗号将值与下面的名称分隔开。对象中的名称应该是惟一的。

...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 can do 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 MUST accept all texts that conform to the JSON grammar. A JSON parser MAY accept non-JSON forms or extensions.

JSON解析器将JSON文本转换为另一种表示形式。JSON解析器必须接受符合JSON语法的所有文本。JSON解析器可以接受非JSON形式或扩展。

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.

实现可以对其接受的文本的大小设置限制。实现可以对嵌套的最大深度设置限制。实现可以对数字的范围设置限制。实现可以对字符串的长度和字符内容设置限制。

...but an implementation doesn't have to 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", "b"), ("a", "c")]
  • ((“a”、“b”)(“a”、“c”)]
  • [("a", ["b", "c"])]
  • ((“a”、“b”,“c”)))
  • []
  • []
  • 42
  • 42
  • "your JSON is bad and you should feel bad"
  • " JSON不好,你应该感觉不好"

...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。如果你想这样做,你必须手工去做——建立你自己的抽象语法树,你自己的解析器,你自己的生成器,为任何想要使用你的数据的人建立生成器……

#2


3  

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的解析器。但这将是惊人的愚蠢。

#3


0  

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)。首先,您需要更好的测试用例。

#4


0  

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字符串的访问权限,您可以轻松地做到这一点,只需将“all”、“”替换为“}、{”并将结果包装为“[”和“]”即可。

You now have a valid JSON array of key/value pairs that is javascript legal.

现在,您有了一个合法的JSON数组的键/值对。