proversion
proversion

Reputation: 593

To remove extra square bracket in json format

I am trying to fetch json data from database and it shows an extra square bracket in the result. Due to this i got error in the result. How to remove this extra bracket from the JSON result.

 [[{"Item_Name":"banana","Unit":"Kg","Price":0,"Discount":0},{"Item_Name":"banana","Unit":"Kg","Price":0,"Discount":0}]]

PHP code

<?php 


    require_once('include/dbConnect.php');

    $sql = "SELECT * FROM Items WHERE User_Id='1011'";

    $r = mysqli_query($con,$sql);

    //$res = mysqli_fetch_array($r);

    $result = array();

    while($res = mysqli_fetch_array($r, MYSQL_ASSOC)) {

        array_push($result,array(
            "Item_Name"=> $res['Item_Name'],
            "Unit" => $res['Unit'],
            "Price" => $res['Price'],
            "Discount" => $res['Discount'])
        );
    }

    echo json_encode($result);

    mysqli_close($con);
?>

Upvotes: 1

Views: 3697

Answers (4)

Belisario Per&#243;
Belisario Per&#243;

Reputation: 637

You can use:

$object = json_encode($array, JSON_FORCE_OBJECT);

Upvotes: 1

proversion
proversion

Reputation: 593

    require_once('include/dbConnect.php');

    $sql = "SELECT Item_Name,Unit,Price,Discount,Remaining_Count FROM Items WHERE User_Id='1011'";

    $r = mysqli_query($con,$sql);

    //$res = mysqli_fetch_array($r);

    $result = array();

            while($row = mysqli_fetch_assoc($r)) {      

                    $result[]=$row; }

    $data =  json_encode($result);
    print_r($data);
    mysqli_close($con);

Upvotes: 0

Yogesh
Yogesh

Reputation: 1585

There's nothing wrong in your PHP code.

Since you are creating an array of array in PHP, hence json_encode is giving you array of array of objects.

To see exact contents of php array use print_r($your_array_variable), don't use echo for printing arrays.

UPDATE 1:

Possible reasons for this could be

An additional call to json_encode() somewhere down in the code

Upvotes: 2

Haibara Ai
Haibara Ai

Reputation: 10897

Updated:

Just replace echo json_encode(array($result)); with echo json_encode($result);

<?php   require_once('include/dbConnect.php'); 
$sql = "SELECT * FROM Items WHERE User_Id='1011'"; 
$r = mysqli_query($con,$sql);
//$res = mysqli_fetch_array($r); 
$result = array(); 
while($res = mysqli_fetch_array($r, MYSQL_ASSOC)) 
{   
    array_push($result,array( "Item_Name"=> $res['Item_Name'], "Unit" => $res['Unit'], "Price" => $res['Price'], "Discount" => $res['Discount']));
} 
echo json_encode($result); 
mysqli_close($con)

If you mean removing the first and last bracket, I believe you just need to get the first value like in an array.

Specific implementation may depend on your programming language.

var A = [[{"Item_Name":"banana","Unit":"Kg","Price":0,"Discount":0}, {"Item_Name":"banana","Unit":"Kg","Price":0,"Discount":0}]];
var B = A[0]; 

Upvotes: 0

Related Questions