php:用ojects创建数组,或者如何去掉多余的引号符号


php: Create array with ojects or how to get rid off extra quotes symbols

我在文件中存储了一些数据,看起来像这个

{"name":"name1","uuid":"uuid1"}
{"name":"name2","uuid":"uuid2"}

与php相比,我使用下一个代码将其转换为JSON

$file = "someData.json";
$content = explode("'r'n", file_get_contents($file));
$output = array( 'someData' => array_values( array_filter($content) ) );
$output = json_encode($output);
echo $output;

在输出中,我得到对象

[ " {"name":"name1","uuid":"uuid1"},{"name":"name2","uuid":"uuid2"} " ]

而不是带有对象的阵列

[{"name":"name1","uuid":"uuid1"},{"name":"name2","uuid":"uuid2"}]

获取带有对象的数组或只删除第一个和最后一个引用的sybols的最佳解决方案是什么?

您的问题下面的注释是正确的。您忽略了将json解码为PHP数据结构的步骤,因此您的每个javascript对象都只是被视为字符串,而不是您想要将其视为的对象/哈希。

与其像现在这样爆炸,不如将其重写为:

$file=file_get_contents("someData.json";)
$content=json_decode($file)
$output=数组('someData'=>array_values(array_filter($content))
$output=json_encode($output)
echo$output

我知道这看起来可能很愚蠢,但使用preg替换确实有效。

$json = '[ " {"name":"name1","uuid":"uuid1"},{"name":"name2","uuid":"uuid2"} " ]";
preg_replace(array("/[ '" {/", "/} '" ]/"), array("[{", "}]"), $json);
感谢您的帮助。我在php方面不是很好,但即使在排除了您的示例中的错误后,我也会做出其他决定。现在,我以这样一种原始的方式回显纯JSON,而不进行任何解码/编码:
$file = "file.json";
$content = file_get_contents($file);
$content = rtrim($content, ",'r'n");
$output = '
        {
            "someData": ['.$someData.']
        }
        ';