Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

201
Views
Format JSON conditionally

I'm trying to learn PHP and am just trying to generate some JSON

This is the format I want it in.

{
    "Data": "Message was sent on 12-31-1999 12:00:00 am",
    "Sandbox": {
        "Sandboxed": true
    },
    "Errors": [{
        "Code": 5,
        "Message": "Message bounced back"
    }]
}

And I can do that with :

$message = "Message was sent on 12-31-1999 12:00:00 am";
$errorMsg = "Message bounced back";

$sandboxkey = array( "Sandboxed" => true );

$error = array( "Code" => 5, "Message" => $errorMsg );

$package = array(
    "Data" => $message,
    "Sandbox" => $sandboxkey,
    "Errors" => $error
);

return json_encode($package, JSON_FORCE_OBJECT | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

But I want to only add the "Sandbox" key/value if a boolean is set.

$isSandbox = true;
$message = "Message was sent on 12-31-1999 12:00:00 am";
$errorMsg = "Message bounced back";
$error = array( "Code" => 5, "Message" => $errorMsg );
$package = array(
    "Data" => $message,
    "Errors" => $error
);
if ($isSandbox) {
    $sandboxkey = array( "Sandboxed" => true );
    array_push($package, $sandboxkey);
}
$error = array( "Code" => 5, "Message" => $errorMsg );
return json_encode($package, JSON_FORCE_OBJECT | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

But that adds a "0" then the KVP.

{
    "Data": "Message was sent on 12-31-1999 12:00:00 am",
    "Errors": {
        "Code": 5,
        "Message": "Message bounced back"
    },
    "0": {
        "Sandboxed": true
    }
}

Additionally, I want the Errors to be listed in an array like:

"Errors": [{
        "Code": 5,
        "Message": "Message bounced back"
    },
            {
        "Code": 4,
        "Message": "Message is old"
    }  ]

I have tried multiple combinations of array push, and JSON_FORCE_OBJECT but I just can't seem to get it exactly how I want. Can anyone help?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

But that adds a "0" then the KVP.

array_push() could be used if the array was a numeric array (i.e. the keys were integers - e.g. 0 => 'cat', 1 => 'dog'. But in this case, the array is an associative array. One way to set the desired key, Sandbox, is to set the array key by specifying it in bracket notation:

if ($isSandbox) {
    $sandboxkey = array( "Sandboxed" => true );
    $package['Sandbox'] = $sandboxkey;
}

This is necessary because the other keys of the array are not

See it demonstrated in this playground example.

Otherwise array_merge() could be used:

if ($isSandbox) {
    $sandboxArray = array(
    'Sandbox' => array( "Sandboxed" => true )
    );
    $package = array_merge($package, $sandboxArray);
}

See a demonstration in this playground example.

Refer to this answer for more information about numeric vs associative arrays. It is somewhat surprising that the difference isn't explicitly spelled out on the PHP Array data type page.

Additionally, I want the Errors to be listed in an array...

For this, nest $error (an associative-array, which will get converted to a JSON object) in another array.

$package = array(
    "Data" => $message,
    "Sandbox" => $sandboxkey,
    "Errors" => array($error)
);
over 4 years ago · Santiago Trujillo Report

0

You have to make few changes in your code, which will help you achieve your expected output.

1. Use array_merge instead of array_push

2. Set Errors key like this "Errors" => array($error) instead of "Errors" => $error

Try this code snippet here

<?php

ini_set('display_errors', 1);
$isSandbox=true;
$message = "Message was sent on 12-31-1999 12:00:00 am";
$errorMsg = "Message bounced back";
$error = array("Code" => 5, "Message" => $errorMsg);
$package = array(
    "Data" => $message,
    "Errors" => array($error)
);
if ($isSandbox)
{
    $sandboxkey = array("Sandboxed" => true);
    $package=array_merge($package, $sandboxkey);
}
echo json_encode($package,JSON_PRETTY_PRINT);

Output:

{
    "Data": "Message was sent on 12-31-1999 12:00:00 am",
    "Errors": [
        {
            "Code": 5,
            "Message": "Message bounced back"
        }
    ],
    "Sandboxed": true
}
over 4 years ago · Santiago Trujillo Report

0

How to handle json:

  • [] are arrays in json
  • {} are objects in json

So to create something like {'data':[{'depperdata':2}]} do

 $a = new stdClass();
 $a->data = array();
 $b = new stdClass();
 $b->deeperdata=2;
 $a->data[0]=$b;
 print_r(json_encode($a,JSON_PRETTY_PRINT));

or

 $a = array('data'=>array(array('depperdata'=>2)));
 print_r(json_encode($a,JSON_PRETTY_PRINT));

What does json_decode

  • if you have an assoc-array it becomes an json_object
  • if you have an indexed array it becomes an json_array
  • if you have an object it becomes an json_object
  • if you have mixed assoc/index array you are getting broken json like your example. property name 0! (prevent that!)

Have a nice day...

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!