仅在PHP中解码JSON的第一级

问题

我有一个要解码的JSON字符串。但是,我只希望解码第一层,其余的JSON应该保留为字符串值,而不是嵌套数组。

使用类似的技术,应将生成的数组(具有嵌套的字符串值)解析回JSON字符串。当连续使用这些解码和编码时,结果应为原始JSON字符串。

简单明了吧?

我也宁愿不解释JSON的嵌套值,因为这些值可能是有效的JSON,也可能不是。如果没有解决办法,那就这样吧。

请注意,所有这些斜杠只是为了使其保持有效的PHP字符串,它们不是输入的一部分。输入中没有转义的引号。

当将这样的JSON字符串放入时:

"{
    \"foo\": \"bar\",
    \"nested\": {
        \"nested_key\": \"nested_value\"
    },
    \"another_top_level_key\": \"some_useful_value\"
}"

这应该是输出:

[
    "foo" => "bar",
    "nested" => "{ \"nested_key\": \"nested_value\" }",
    "another_top_level_key" => "some_useful_value"
]

When using var_dump, it should look like this:

array(3) {
  ["foo"]=>
  string(3) "bar"
  ["nested"]=>
  string(32) "{ "nested_key": "nested_value" }"
  ["another_top_level_key"]=>
  string(17) "some_useful_value"
}

Pay attention to the fact that when using var_dump, the quotes are not escaped and thus no slashes exist in the string (the nested quotes are not escaped).

当该数组通过第二个函数(编码器)运行时,应返回原始JSON字符串。

我尝试过的事情:

  • I tried setting the $depth of json_decode() to 1. This, however, only throws exceptions when the limit has been reached.
  • I tried decoding the whole string using json_decode() and then looping over the top-level key-value pairs to run json_encode() over any value that is an array (which should indicate a nested value). The end result was fine at first, but when converting back to a JSON string it escaped the double quotes with slashes. In that case, the end result isn't the same as the original, as the end result includes slashes.

笔记

Even though this question has a very similar title to this one, that one doesn't actually contain answers for its title. There is only an answer on how to transform the invalid JSON string to a valid JSON.

我宁愿不使用任何RegEx,因为这只会使我的生活变得比它所需要的更加复杂;)。但是,如果无法避免,那就是我的生活。

评论