0

I am getting a nested json object back from an api call and I am trying to save it to a newline delimited json file so it can be imported into Google Big Query.

Here is what I have and it saves it to my file but still not correctly formatted for Big Query to import it.

    $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);
    }

I have also just tried to save the json to a file but get same error when trying to import to big query.

user1535268
  • 121
  • 1
  • 2
  • 10
  • What error you get? – SergkeiM Sep 13 '19 at 19:34
  • Error while reading data, error message: Failed to parse JSON: No object found when new array is started.; BeginArray returned false; Parser terminated before end of string – user1535268 Sep 13 '19 at 19:40
  • Try to debug the response, it seems like json returned fom API is not correct. `$body = json_decode($response->getBody(), true); dd($body); ` Passing 3rd params as true will make `array` not object. – SergkeiM Sep 13 '19 at 19:42
  • I get a nested array that goes 4 levels deep. – user1535268 Sep 13 '19 at 19:48

1 Answers1

0

pass true value to second parameter of json_decode() method to return associate array like this:

  $results = json_decode($response->getBody()->getContents(),true);
Ahmed Atoui
  • 1,506
  • 1
  • 8
  • 11