0

我有一个这样的json输出代码:

{"a":{"p1":"1"},"a":{"p2":"2"},"b":{"b1":"b2"}}

如何使用 javascript 或 jquery 或 php 将其转换为以下?

{"a":{"p1":"1","p2":"2"},"b":{"b1":"b2"}}

编辑:我通过此代码生成 json 代码:

parts2.push('"'+$(this).attr('alt')+'":{"'+$(this).attr('title') + '"' + ":" + '"'+$(this).attr('value') + '"}' );

但是 $(this).attr('alt') 可能会在循环中重复,我想防止重复键,而是将值附加到该键

4

3 回答 3

4

Each property of an object is supposed to have a unique key name. If you try to parse JSON with duplicate key names, only the last occurring value is used, so it isn't possible to parse this with the native JSON.parse and still expect data to be preserved.

As per your edit, you can prevent the duplicates from ever occurring:

var obj = {};

if typeof obj[$(this).attr('alt')] == "undefined"
    obj[$(this).attr('alt')] = {};

obj[$(this).attr('alt')][$(this).attr('title')] = $(this).attr('value');
parts2.push(JSON.stringify(obj));
于 2012-11-26T11:05:21.407 回答
2

您应该在生成 JSON 字符串之前合并该值,或者您必须自己实现 JSON 解析器来解析您的 JSON。

http://www.ietf.org/rfc/rfc4627.txt?number=4627

对象中的名称应该是唯一的

于 2012-11-26T11:14:41.120 回答
1

无需对伪 JSON 进行字符串化,只需创建一个对象,填充该对象,然后在发送对象时将其字符串化:

var parts = {};
$('.foo')each(function()
{//the loop, here parts is being filled
    parts.[$(this).attr('alt')] = parts.[$(this).attr('alt')] || {};//initialize to object if property doesn't exist
    parts.[$(this).attr('alt')] = [$(this).attr('title')] = $(this).attr('value');
});
//make JSON:
partsJSON = JSON.stringify(parts);
//{a:{p1:foo,p2:bar},b:{p3:foobar}} or something
于 2012-11-26T11:15:13.753 回答