Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Manipulate JSON node to have [] parentheses

Json response from 3rd party platform which I cant control.

$json = '{
  "question1": "answera",
  "question2": [
       "answerb",
       "answerc"]
}';

Any ‘question’ can have multiple ‘answers’, however if there is only one ‘answer’ for that question the response comes back without the [] parentheses – this is breaking the insert into the next system (that I also dont have control over) as it is expecting the [].

Using PHP is there a way to manipulate the json string to be the following, irrelevant of the number of ‘answers’:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"question1": ["answera"],

>Solution :

You can convert string contents into an array. But you habe to iterate over all answers for this purpose.

<?php
$json = '{
  "question1": "answera",
  "question2": [
       "answerb",
       "answerc"
  ]
}';

// second parameter for array result
$array = json_decode($json, true);

foreach ($array as $question => $answer) {
    if (is_string($answer) === true) {
        $array[$question] = [ $answer ];
    }
}

This one results into …

array(2) {
  'question1' =>
  array(1) {
    [0] =>
    string(7) "answera"
  }
  'question2' =>
  array(2) {
    [0] =>
    string(7) "answerb"
    [1] =>
    string(7) "answerc"
  }
}

For any further JSON processing you can convert the PHP array back into JSON.

$json = json_encode($array);

Results into …

string(109) "{
    "question1": [
        "answera"
    ],
    "question2": [
        "answerb",
        "answerc"
    ]
}"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading