json boolean转换为字符串

时间:2022-03-16 01:51:12

I have the following .json (saved as a file named: settings.json):

我有以下.json(保存为名为:settings.json的文件):

[{"compact": false, "noPadding": true}]

On click, I want to change the boolean for "compact" to its opposite state. This is my function to do it (theres a little bit of react in there, but i think it shouldnt matter for my question):

点击后,我想将“compact”的布尔值更改为相反的状态。这是我的功能(在那里有一点反应,但我认为这对我的问题不重要):

onClick={editJson(this, "settings", "compact", this.context.settings[0]["compact"], !this.context.settings[0]["compact"])}

Which performs the following function:

其中执行以下功能:

function editJson(component, filename, field, oldvalue, newvalue) {
    var json = component.state[filename] || [];
    var i;
    for (i = 0; i < json.length; i++) {
        if (json[i][field] === oldvalue) {
            json[i][field] = newvalue
        }
    }
    $.post('json/write.php', {filename: filename + '.json', data: json}).then(function (data) {
        queryJson(component, filename);
    });
}

Which then writes back to my .json by performing write.php:

然后通过执行write.php写回我的.json:

<?php
file_put_contents($_POST['filename'], json_encode($_POST['data']));
return ($_POST['data']);

But now my booleans have become strings (which I dont want):

但现在我的布尔变成了字符串(我不想要):

[{"compact": "true","noPadding": "true"}]

I assume the problem is either with javascripts weak typing or my php, but i cant figure out the solution.

我认为问题是javascripts弱打字或我的PHP,但我无法找出解决方案。

How can I keep my booleans as booleans in this scenario?

在这种情况下,如何将布尔值保持为布尔值?

1 个解决方案

#1


2  

The problem is that POST data is always a string. That's just how it works...

问题是POST数据总是一个字符串。这就是它的工作原理......

But you could iterate through your POST data and use PHP's filter_var to convert the strings to boolean

但是你可以遍历你的POST数据并使用PHP的filter_var将字符串转换为boolean

filter_var(YOUR_POSTDATA, FILTER_VALIDATE_BOOLEAN);

#1


2  

The problem is that POST data is always a string. That's just how it works...

问题是POST数据总是一个字符串。这就是它的工作原理......

But you could iterate through your POST data and use PHP's filter_var to convert the strings to boolean

但是你可以遍历你的POST数据并使用PHP的filter_var将字符串转换为boolean

filter_var(YOUR_POSTDATA, FILTER_VALIDATE_BOOLEAN);