简体   繁体   English

json_decode失败

[英]json_decode failing

I have the following JSON formatted string: 我有以下JSON格式的字符串:

{

"hooks":[
        {
        "type":"subscribe",
        "id":1331741592.6925,
        "email":"JoeX@test-email.com",
        "status":"Active",
        "custom_fields":"{\"first_name\":\"Joe\",\"last_name\":\"X\"}",
        "ip_created":"24.199.200.142",
        "list_id":"33",
        "list_type":"internal",
        "list_name":"Administrator List 2",
        "list_optin":false
        },
        {
        "type":"subscribe",
        "id":1331741592.7067,
        "email":"JaneY@test-email.com",
        "status":"Active",
        "custom_fields":"{\"first_name\": \"Jane\",\"last_name\":\"Y\"}",
        "ip_created":"24.199.200.142",
        "list_id":"33",
        "list_type":"internal",
        "list_name":"Administrator List 2",
        "list_optin":false
        }
    ]

}

I want to use the PHP json_decode() function to put it in an associative array. 我想使用PHP json_decode()函数将其放入关联数组中。

When I do run the script, debugging shows the value of the new array as null , so I presume the decode is failing. 当我运行脚本时,调试将新数组的值显示为null ,因此我认为解码失败。 We aren't running PHP 5.3, so I can't use json_last_error() . 我们没有运行PHP 5.3,所以我不能使用json_last_error() Here is the code: 这是代码:

$hooks = (the JSON string from above);
$hooksArray = json_decode($hooks, true);

Any ideas why the $hooksArray is coming back null ? 任何想法为什么$hooksArray返回null

Is the JSON string inside your PHP source? JSON字符串是否在您的PHP源代码中? Perhaps it's not interpreting the escaped backslashes correctly. 也许不是正确地解释了转义的反斜杠。

I tried the following experiment in Python for reference: Dumped the JSON data into a multi-line string via the REPL and decode it with json.loads(). 我尝试在Python中进行以下实验以供参考:通过REPL将JSON数据转储为多行字符串,并使用json.loads()对其进行解码。 It choked on the in-string quotes in the first instance of the custom_fields string. 它阻塞了custom_fields字符串的第一个实例中的字符串内引号。 When I examined the multi-line string, all the escapes were gone, leaving me only with the quotes. 当我检查多行字符串时,所有转义符都消失了,只剩下引号了。

When I put the same JSON data in an external file and loaded it, it worked fine. 当我将相同的JSON数据放入外部文件并加载时,它工作正常。

I put the JSON data in an external file and replaced all '\\"' instances with '\\\\"' and then the first experiment started to work. 我将JSON数据放在一个外部文件中,并用'\\\\“'替换了所有'\\”实例,然后第一个实验开始工作。

Maybe that will work for you too. 也许这也会为您服务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM