JSON解析多个密钥 [英] JSON parse multiple key

查看:172
本文介绍了JSON解析多个密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下JSON字符串.

I have the following JSON String.

var jsonString = '{"J":4,"0":"M", "J":5,"0":"N"}'

如果我使用jquery.parseJSON(jsonString)进行解析,则会得到

If I parse it using jquery.parseJSON(jsonString) I get

{"J":5,"0":"N"}

问题

1)jsonString格式不正确吗?

1) Is jsonString malformed?

2)是否可以使用另一种jquery方法来包含具有重复键的对象,即

2) Is there another jquery method I can use to include objects with duplicate keys, i.e.

jquery.someAwesomeMethod(jsonString) => {"J":4,"0":"M", "J":5,"0":"N"}

推荐答案

直接回答您的问题:

1) Is jsonString malformed?

它实际上可能是合法的JSON(我不太确定),但由于键重复,因此在任何类型的javascript上下文中使用或与任何JavaScript JSON解析器(如jquery.parseJSON)一起解析时,它都不实用.

It may actually be legal JSON (I'm not totally sure), but it will not be practical when used in any sort of javascript context or when parsed with any javascript JSON parser like jquery.parseJSON because of the duplicate keys.

2) Is there another jquery method I can use to include objects 
   with duplicate keys, i.e.

jquery.someAwesomeMethod(jsonString) => {"J":4,"0":"M", "J":5,"0":"N"}

,没有这样的jQuery方法,这既是因为jQuery没有这种方法,也是因为您无法在javascript中获得所需的输出.您已经表示了Javascript对象语法,但是Javascript对象不支持重复键.在Javascript中,为给定键设置的最后一个值将获胜.

No, there is no such jQuery method both because jQuery doesn't have that and because the output you desire is not possible in javascript. You've represented a Javascript object syntax, but Javascript objects don't support duplicate keys. In Javascript, the last value set for a given key wins.

因此,如果您打算将JSON解析为普通的javascript对象(浏览器应用中通常如何使用JSON以及如何使用jquery.parseJSON()解析JSON),则不会获得具有该类型数据声明的重复键因为以后使用相同密钥的声明可能会替换以前的声明-只有一个可以生存.

So, if you intend to parse the JSON into a normal javascript object (how JSON is normally used in a browser app and how it is parsed with jquery.parseJSON()), you will not get duplicate keys with that type of data declaration as later declarations of the same key will likely just replace earlier declarations - only one will survive.

您可能想要一些不同类型的数据结构,例如数组或具有键的数组值的对象:

You probably want some different type of data structure such as an array or an object with array values for the keys:

这是一个仅在键和值之间成对交替的数组:

Here's an array that just alternates between keys and values in pairs:

[
    "J", 4, 
    "0","M", 
    "J", 5, 
    "0","N"
]

obj[0] // key
obj[1] // corresponding value

访问数组时,偶数索引将是键,奇数索引将是值.

When accessing the array, the even indexes would be keys, the odd indexes would be values.

或者这是一个对象,其中的值是数组,因此每个键可以有多个值:

Or here's an object where the values are arrays so you can have more than one value per key:

{"J":[4, 5], "0":["M", "N"]}

typeof obj["J"]  // Array
obj["J"].length  // array of length == 2
obj["J"][0]      // first value in array == 4
obj["J"][1]      // second value in array == 5

每个键将包含一个值数组.

Each key would hold an array of values.

这篇关于JSON解析多个密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆