Decode the String having same key

{"": "attachment-2","": "attachment-1"}

I am getting this JSON-encoded string (or an oher format... let me know) from parsing a mail and I can not change it. How can I decode it?


This JSON response is invalid as @ThiefMaster mentioned, because JSON doesn't support duplicated keys .

You should contact the service you're trying to request this response from.

In case you have a valid JSON response you can decode it using the json_decode function which returns an object or an array (depends on the second parameter);

For example: (Object)

$json_string = '{"keyOne": "attachment-2","keyTwo": "attachment-1"}';
$decoded = json_decode($json_string);

print $obj->keyOne; //attachment-2
print $obj->keyTwo; //attachment-1

Another option is to write your own decoder function.


You cannot use a JSON parser for this as it will always overwrite the first element due to the same keys. The only proper solution would be asking whoever creates that "JSON" to fix his code to either use an array or an object with unique keys.

If that's not an option the only thing you can do it rewriting the JSON to have unique keys before parsing it using json_decode()

Assuming it always gives you proper JSON and the duplicate keys are always empty you can replace "": with "random-string": - preg_replace_callback() is your friend in this case:

$lame = '{"": "attachment-2","": "attachment-1"}';
$json = preg_replace_callback('/"":/', function($m) {
    return '"' . uniqid() . '":';
}, $lame);
var_dump(json_decode($json));

Output:

object(stdClass)#1 (2) {
  ["5076bdf9c2567"]=>
  string(12) "attachment-2"
  ["5076bdf9c25b5"]=>
  string(12) "attachment-1"
}

解码它自己?

$myStr = '{"": "attachment-2","": "attachment-1"}';
$vars = explode(',',$myStr);
$arr = array();
foreach($vars as $v){
    list($key,$value) = explode(':',$v);
    $key = substr($key,strpos($key,'"'),strpos($key,'"')-strrpos($key,'"'));
    $value = substr($value,strpos($value,'"'),strpos($value,'"')-strrpos($value,'"'));
    if($key=='')$arr[] = $value;
    else $arr[$key] = $value;
}
链接地址: http://www.djcxy.com/p/37842.html

上一篇: 使用重复键处理JSON

下一篇: 解码具有相同密钥的字符串