Skip to content
Advertisement

Turning a CSV into a nested JSON object in PHP, Drupal 8

I’m trying to turn a CSV into a JSON object made of nested arrays for each row within the file.

I’ve tried a handful of similar SO questions but haven’t found quite the right solution.

I’m attempting to set up a JSON object with a handful of nested objects, based on the first value in each row of the CSV.

My CSV file, titled data_source.csv looks like:

JavaScript

My PHP code (in a controller in Drupal 8):

JavaScript

The ideal situation would be a single JSON object with a series of nested objects, like:

JavaScript

Is my PHP code set up as effectively as possible?

When I run this on my local environment, I receive an error message that reads: ‘LogicException: The controller must return a response ([the json object])’

So my JSON object is included in the error message, which is encouraging but it’s unclear why it’s part of a LogicException.

Advertisement

Answer

Maybe you need to return a JsonResponse

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement