I’m trying to json_decode a JSON package from the database and then explode one of the properties by ‘n’ as follows. I’m in laravel so I’ve dd’d all the variables as they go through the process
$options = json_decode($field['options'],true);
$rows = explode('n', $options['choices']);
dd($field['options'],$options,$rows,'here');
See the screenshot of the printed results. $field[‘options’] looks like a good JSON string.
When decoded, $options has extra quote marks added.
Exploding the weird string doesn’t work.
Tried to JSON decode an object and returned extra quote marks in the string, now I can’t explode the string.
3
Answers
OK so the extra quote marks were a bit of a curve-ball...
There was nothing wrong with the json_decode as @pickuse mentioned.
The issue was with the explode. Instead of using 'n' as the delimiter, you should use PHP_EOL as follows:
This may help, but there would be a problem that I just noticed after submitting this the first time.
Mine reads a file so I needed to trim all the returns, trim($line) and also I stripped out all n, str_replace("n",”,$line).
This will likely to cause a problem with array:2[choices => and Array:1 [0 => as the n is the delimiter. So you’re going to need to encapsulate those values.
This is what I wrote a while back to turn json into yaml. I trim each line, contact the string then strip all new lines "n" and then decode the long json string.
10 lines from the rewbin-test.json file. In the file there are returns.
In the $data var there are no returns.
That portion in the array.
Hope this is helpful.
rew
Your problem is using the single quote for the
n
, it will NOT interpret tonewline
, you need using double quote.Reference: https://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.double
No problems with my code to extract the multiline data
Output: