问题描述
我有一个包含JSON字符串的数组.
I have an array that contains a JSON string.
Array
(
[0] => Array
(
[name] => Original
[nutrients] => {"calories":{"value":2500,"operator":2},"protein":{"value":500,"operator":1},"carbs":{"value":200,"operator":0},"fat":{"value":50,"operator":0},"sugar":{"value":1,"operator":2}}
)
[1] => Array
(
[name] => Rest
[nutrients] => {"calories":{"value":5000,"operator":2},"sugar":{"value":10,"operator":2}}
)
)
我想将整个数组转换为JSON字符串
I want to turn the whole array into a JSON string
echo json_encode($array);
但这会在所有引号前面引发\
But this throws a \
in front of all quotes
[{"name":"Original","nutrients":"{\"calories\":{\"value\":2500,\"operator\":2},\"protein\":{\"value\":500,\"operator\":1},\"carbs\":{\"value\":200,\"operator\":0},\"fat\":{\"value\":50,\"operator\":0},\"sugar\":{\"value\":1,\"operator\":2}}"},{"name":"Rest","nutrients":"{\"calories\":{\"value\":5000,\"operator\":2},\"sugar\":{\"value\":10,\"operator\":2}}"}]
出现此问题是因为营养值已经是JSON字符串.
This problem comes about because the nutrients value is already a JSON string.
当数组已经包含JSON字符串且引号前没有斜杠时,如何将其转换为JSON字符串?
How can I convert an array into a JSON string when it already contains JSON strings, while having no slashes in front of the quotes?
推荐答案
如果要将JSON值保留为字符串;那么,你就不能,而且你不应该能够!
If you want to preserve the JSON values as strings; then, you can't, and you shouldn't be able to!
如果您的数组已经包含一些JSON值(其中将带有一些引号:"
),并且您想将该数组编码为JSON字符串,则引号必须正确地逃脱,正确地得到什么;否则,由于缺少引号匹配,整个JSON字符串将被破坏.
If your array already contains some JSON values (in which they'll have some quotation marks: "
) and you want to encode that array into a JSON string, then the quotation marks must be properly escaped, what you get correctly; otherwise, the entire JSON string will be corrupt because of miss-quotation-mark matches.
这是因为"
在JSON中具有特殊含义,但是\"
表示双引号字符" 不是"
的特殊标记;例如,从有效的JSON字符串中删除反斜杠肯定会导致一些语法错误:
That's because the "
has a special meaning in JSON, but the \"
means the "double quotation mark character" not the special token of "
; for example, removing the backslashes from the valid JSON string causes some syntax errors for sure:
$json = '[{"name":"Original","nutrients":"{\"calories\":{\"value\":2500,\"operator\":2},\"protein\":{\"value\":500,\"operator\":1},\"carbs\":{\"value\":200,\"operator\":0},\"fat\":{\"value\":50,\"operator\":0},\"sugar\":{\"value\":1,\"operator\":2}}"},{"name":"Rest","nutrients":"{\"calories\":{\"value\":5000,\"operator\":2},\"sugar\":{\"value\":10,\"operator\":2}}"}]';
$json_noBackslashes = str_replace('\\', '', $json);
$json_decoded = json_decode($json_noBackslashes);
echo json_last_error_msg(); // Syntax error
这篇关于当数组已经包含JSON字符串时,将数组转换为JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!