1

I have an unusual situation where depending on the value of active being 0 or 1 causing invalid JSON to be interpreted client side. How can I change value active from an int to string within the array so that json_encode is valid? Or is it something else entirely? Looking at both json outputs look identical...

Active and ID are both integers. Everything else is a string.

Interestingly enough, if active is 1 instead of 0 the JSON is valid and displays properly.

JSON:

[
  {
    "id": 254,
    "name": "Test",
    "company": "Test",
    "email": "Test",
    "phone": "Test",
    "comments": "Test",
    "ticket": "Test",
    "assigned": "",
    "active": 0,
    "date_created": "2018-12-02 00:56:49"
  }
]

Code:

$stmt = $conn->prepare("SELECT id, name, company, email, phone, comments, ticket, assigned, active, date_created FROM tickets_info");
$stmt->execute();

$result = $stmt->get_result();
$result_array = array();

while ($row = $result->fetch_assoc()) {
    array_push($result_array, $row);
}

header("Content-Type: application/json"); 

echo json_encode($result_array);
3
  • 2
    Please update your question with how the comparison is done client-side and the error that is thrown there. I don't see that the current JSON array that you have shared is invalid. Commented Dec 2, 2018 at 6:58
  • I receive valid json client-side when integers are converted to string. How can I convert id and active to strings within the array? Commented Dec 2, 2018 at 7:01
  • I copied the above json to an online validator and it said your json was valid. I don't think there is anything wrong with your server side code. Commented Dec 2, 2018 at 7:09

1 Answer 1

3

As your question that you need to cast int to string

It's easy just cast it

while ($row = $result->fetch_assoc()) {
       $row['id'] = (string) $row['id'] ;
       $row['active'] = (string) $row['active'] ;
       array_push($result_array, $row) ;
} 

CASTING are very easy to change data type

We can cast following data type variable in PHP

(int), (integer) - cast to integer

(bool), (boolean) - cast to boolean

(float), (double), (real) - cast to float

(string) - cast to string

(array) - cast to array

(object) - cast to object

(unset) - cast to NULL (PHP 5)

Reference https://www.greycampus.com/codelabs/php/type-casting

Sign up to request clarification or add additional context in comments.

2 Comments

Sorry, let me be clear. I would like to change id and active from integers to strings. How can this be done inside the array?
Please check answer I updated it with casting