0

我有一个格式错误的 JSON 文件(doc1.json):

{"text":"xxx","user":{"id":96525997,"name":"ss"},"id":29005752194568192}
{"text":"yyy","user":{"id":32544632,"name":"cc"},"id":29005753951977472}
{...}{...}

我必须改变它:

{"u":[
{"text":"xxx","user":{"id":96525997,"name":"ss"},"id":29005752194568192},
{"text":"yyy","user":{"id":32544632,"name":"cc"},"id":29005753951977472},
{...},{...}
]}

我可以在 PHP 文件中执行此操作吗?

4

2 回答 2

1
//Get the contents of file
    $fileStr = file_get_contents(filelocation);

//Make proper json
    $fileStr = str_replace('}{', '},{', $fileStr);

//Create new json    
    $fileStr = '{"u":[' . $fileStr . ']}';

//Insert the new string into the file
    file_put_contents(filelocation, $fileStr);
于 2015-05-20T14:28:41.533 回答
0

我会从文件中构建你想要的数据结构:

$file_path = '/path/to/file';
$array_from_file = file($file_path);

// set up object container
$obj = new StdClass;
$obj->u = array();

// iterate through lines from file
// load data into object container
foreach($array_from_file as $json) {
    $line_obj = json_decode($json);
    if(is_null($line_obj)) {
        throw new Exception('We have some bad JSON here.');
    } else {
        $obj->u[] = $line_obj;
    }
}

// encode to JSON
$json = json_encode($obj);

// overwrite existing file
// use 'w' mode to truncate file and open for writing
$fh = fopen($file_path, 'w');
// write JSON to file
$bytes_written = fwrite($fh, $json);
fclose($fh);

这假定原始文件中的每个 JSON 对象表示都在单独的行上。

我更喜欢这种方法而不是字符串操作,因为您可以在解码 JSON 的位置进行内置检查,以查看输入是否是可以反序列化的有效 JSON 格式。如果脚本成功运行,这保证了您的输出将能够被脚本的调用者反序列化。

于 2015-05-20T14:34:15.723 回答