解码具有相同密钥的字符串

Tec*_*e99 0 php json

{"": "attachment-2","": "attachment-1"}
Run Code Online (Sandbox Code Playgroud)

我通过解析邮件得到这个 JSON 编码的字符串(或其他格式...让我知道),但我无法更改它。我怎样才能解码它?

Thi*_*ter 5

您不能为此使用 JSON 解析器,因为由于相同的键,它总是会覆盖第一个元素。唯一正确的解决方案是要求创建该“JSON”的人修复其代码,以使用数组或具有唯一键的对象。

如果这不是一个选项,那么您唯一可以做的就是在使用解析之前重写 JSON 以具有唯一的键json_decode()

假设它总是为您提供正确的 JSON 并且重复的键始终为空,您可以替换"":"random-string":-preg_replace_callback()在这种情况下是您的朋友:

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

输出:

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