【问题标题】:Save json api results to json file in newline delimited format using php使用php将json api结果以换行符分隔格式保存到json文件
【发布时间】:2019-09-13 19:32:36
【问题描述】:

我从一个 api 调用中获取了一个嵌套的 json 对象,我正在尝试将它保存到一个以换行符分隔的 json 文件中,以便可以将其导入到 Google Big Query 中。

这是我所拥有的,它会将其保存到我的文件中,但仍然没有正确格式化以便 Big Query 导入它。

    $response = $this->client->post($url);

    $results = json_decode($response->getBody()->getContents());
    $date = Carbon::now()->toDateString();

    $filename = 'resources/results-' . $date . '.ndjson';

    foreach ($results as $result) {
        $newline = json_encode($result) . "\n";
        file_put_contents(base_path($filename), $newline, FILE_APPEND);
    }

我也刚刚尝试将 json 保存到文件中,但在尝试导入大查询时遇到同样的错误。

【问题讨论】:

  • 你遇到什么错误?
  • 读取数据时出错,错误信息:无法解析JSON:启动新数组时未找到对象。;开始数组返回假;解析器在字符串结束之前终止
  • 尝试调试响应,好像json返回fom API不正确。 $body = json_decode($response->getBody(), true); dd($body); 将第三个参数作为 true 传递将使 array 不是对象。
  • 我得到了一个 4 层深的嵌套数组。

标签: php json laravel google-bigquery ndjson


【解决方案1】:

将 true 值传递给 json_decode() 方法的第二个参数以返回关联数组,如下所示:

  $results = json_decode($response->getBody()->getContents(),true);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-20
    • 1970-01-01
    • 2021-03-22
    • 1970-01-01
    • 2021-11-08
    • 2015-10-04
    • 1970-01-01
    • 2021-01-28
    相关资源
    最近更新 更多