简体   繁体   English

如何避免json_decode将true和false转换为0和1?

[英]How do I keep json_decode from turning true and false into 0's and 1's?

I have this JSON string from reddit: http://www.reddit.com/.json . 我有来自reddit的JSON字符串: http : //www.reddit.com/.json I am trying to get the "likes" field from this. 我正在尝试从中获得“喜欢”字段。

My problem is reddit uses "false" for the likes field, and "0" / null when there is nothing liked or unliked. 我的问题是reddit在likes字段中使用“ false”,在没有任何喜欢或不同之处时使用“ 0” / null。 When I use json_decode, it takes the "likes" field and changes the false to null if it is not liked. 当我使用json_decode时,它将接受“喜欢”字段,如果不喜欢,则将false更改为null。 This causes me an issue, because now I can't tell if the post is disliked by the user or neutral. 这给我带来了一个问题,因为现在我无法确定该帖子是用户不喜欢还是中立。

I thought of replacing all of the "false" in the JSON string to "dislikes", but this doesn't work because if there is "false" in the post text, then that will be replaced as well. 我曾想将JSON字符串中的所有“假”替换为“不喜欢”,但这是行不通的,因为如果帖子文本中存在“假”,那么也将被替换。

                // what i have right now
                $response = str_replace("false", "\"dislikes\"", $output); 
                $out = json_decode($response, true);

How do I keep json_decode from changing "false" to 0? 如何防止json_decode从“ false”更改为0?

You cannot change "false" to "dislikes".. 您不能将“假”更改为“不喜欢”。
The reason is in your json it is false not "false" meaning the false in your json is in boolean type.. 原因是在json中为false而不是"false"这意味着json中的false为布尔类型。

if you really want to change it modify the original array that was json_encoded : 如果您真的要更改它,请修改原始数组json_encoded

sample: 样品:

// assuming this is your original array

$orginal_array = array("your_key" => false);

// change it to

$new_array = array("your_key" => "false");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM