Codezzz
Codezzz

Reputation: 245

How to remove the Square Bracket in JSON using PHP

Below code is the returned JSON

[{"one":"id","two":"id","three":"id"},{"one":"id","two":"id","three":"id"}]

Below code is the desired result of the returned JSON (without the array bracket)

{"one":"id","two":"id","three":"id"},{"one":"id","two":"id","three":"id"}

Below code is to convert the array to the JSON format

include('connect-db.php'); 
$result = mysql_query("SELECT * FROM patientvaccinedetail"); 
$specific = []; 
while($row = mysql_fetch_array( $result ,MYSQL_ASSOC)) { 
echo "<tr>"; 
echo '<td width="100px">' . $row['id'] . '</td>'; 
echo '<td width="200px">' . $row['patientid'] . '</td>'; 
echo '<td width="200px">' . $row['vaccineid'] . '</td>'; 
  //**********Convert the array into json******************* 

  $specific[] = ["one" => $row["id"],
                 "two" => $row["patientid"],
                 "three" => $row["vaccineid"]];

$result = json_encode($specific,JSON_UNESCAPED_UNICODE);

echo $result;
echo "</tr>";
echo "</table>";
?>

To send the request to the API, iam using Guzzle And the format the API require is {xx:xx},{xx:xx} without the square bracket, any idea how to remove it using PHP. Thanks in advance

     $client = new Client([
    'headers' => ['Content-Type' => 'application/json',
                  'Token' => $token]
                           ]);

       $response = $client->post('http://localhost:91/Religious',
       ['body' => ***Where the json will be place***]
       );

Upvotes: 5

Views: 22887

Answers (8)

Alex Taylor
Alex Taylor

Reputation: 131

This will remove the outer wrapper without disturbing any inner wrappers:

$wrapped = <<<EOD
[{"one":"id","two":"id","three":"id"},{"one":"id","two":"id","three":"id"}]
EOD;

$array = json_decode($wrapped, true);
$unwrapped = json_encode($array, JSON_FORCE_OBJECT);

print_r($unwrapped);
// {"0":{"one":"id","two":"id","three":"id"},"1":{"one":"id","two":"id","three":"id"}}

Upvotes: 0

ucMax
ucMax

Reputation: 5458

You are trying to convert a PHP array to a JSON array, so php wrap the result in brackets, it's totally normal. If you need a JSON object Then I would suggest to use JSON_FORCE_OBJECT as additional option(parameters) in json_encode.

$object = json_encode($array, JSON_FORCE_OBJECT);

Upvotes: 2

Sajjad Aljileezi
Sajjad Aljileezi

Reputation: 794

you can trimit see example below trim($data, '[]')

Upvotes: 1

tlorens
tlorens

Reputation: 532

I've added comments as to what the OP is trying to do. But here's my solution for future visitors of this question.

class Thing implements \JsonSerializable
{
    private $name;
    private $description;
    private $code;

    /**
     * Get the value of name
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set the value of name
     *
     * @return  self
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get the value of description
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * Set the value of description
     *
     * @return  self
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get the value of code
     */
    public function getCode()
    {
        return $this->code;
    }

    /**
     * Set the value of code
     *
     * @return  self
     */
    public function setCode($code)
    {
        $this->code = $code;

        return $this;
    }

    public function jsonSerialize()
    {
        $vars = get_object_vars($this);

        return $vars;
    }
}

$thing = new Thing();
$thing->setName('Name');
$thing->setDescription('Description');
$thing->setCode('Code');

$results['items'] = [
    'thing1' => $thing,
    'thing2' => $thing
];

echo json_encode($results);

Here's the output

{
    "items": {
        "thing1": {
            "name": "Name",
            "description": "Description",
            "code": "Code"
        },
        "thing2": {
            "name": "Name",
            "description": "Description",
            "code": "Code"
        }
    }
}

Upvotes: 0

Sterlingking
Sterlingking

Reputation: 200

You might need to use the implode function after a json decode. for example:

implode(',',json_decode($text_from_db or $array))

for example $text_from_db=["rice","beans"]

the result will be- rice,beans

Upvotes: 1

Andrew Owusu
Andrew Owusu

Reputation: 11

Try this

str_replace(array('[', ']'), '', htmlspecialchars(json_encode($result), ENT_NOQUOTES));

Upvotes: 1

K&#233;vin Bibollet
K&#233;vin Bibollet

Reputation: 3623

I read a nice solution in the comments of the first post by deceze ♦ with trim().

$yourJson = trim($yourJson, '[]');

You can also use regular expression:

// if nothing is found, your json has already no brackets or is invalid.
if (preg_match('/^\[(.+)\]$/', $yourJson, $new))
{
    /**
     * $new[0] = $yourJson
     * $new[1] = what's in the parenthesis
     */
    $yourJson = $new[1];
}

Or, you may use substr():

$yourJson = substr($yourJson, 1, strlen($yourJson) - 2);

EDIT: When it says in the request body format : application/json, I do not think that you have to remove the brackets. Did you even try with them?

Upvotes: 17

Rutvik Bhatt
Rutvik Bhatt

Reputation: 486

My suggestion is to use JSON string and perform String operations to remove all those not required characters.

Reason for doing this, the required output is not a valid JSON and won't be accepted by API. As you need it however, I would suggest you to convert the array into json using json_encode and then perform string operations to convert it into your desired output.

Upvotes: -1

Related Questions