Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql / PHP / json_encode boolean string conversion

Tags:

json

php

mysql

I have a mysql query lets say:

SELECT cca_id AS id, cca_title AS text,IF((SELECT count(*) from crm_categories WHERE cca_id_prev = id),'TRUE','FALSE') AS children FROM crm_categories WHERE...

now I get an array back with true / false as a string

If I use json_encode the result is like {"id":"false"}

But I need true/false without quotes - the problem is if i use true false in the mysql query as a boolean it returns 0/1 - but I don't want that either...

Of course I can run a str_replace to the json string - but i think there are alternatives isn't it?

like image 329
sintakonte Avatar asked Apr 18 '14 11:04

sintakonte


People also ask

What does the PHP function json_encode () do?

The json_encode() function is used to encode a value to JSON format.

Is json_encode a string?

json_encode() to convert data to string Json is a data exchange format like XML. You can learn about Json support of PHP here. json_encode function takes data and converts them to a string, we call it as Json string.

What does json_encode return?

The json_encode() function can return a string containing the JSON representation of supplied value. The encoding is affected by supplied options, and additionally, the encoding of float values depends on the value of serialize_precision.

What is JSON encoded string?

The method JSON. stringify(student) takes the object and converts it into a string. The resulting json string is called a JSON-encoded or serialized or stringified or marshalled object.


1 Answers

Well, you are selecting from the database as string. So that's what gets encoded. Use SQL true/false boolean values, which in PHP become 0/1, and cast them to PHP booleans before JSON encoding them:

$data['id'] = (bool)$data['id']; // 0/1 -> PHP false/true

echo json_encode($data); // {'id':true}
like image 150
deceze Avatar answered Oct 27 '22 00:10

deceze