1

I have the following .json (saved as a file named: 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):

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:

<?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.

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

1
  • 1
    POST data is always a string. You may need to loop over the data and cast or just cast them individually before encode. It would be easier to cast 0 and 1. Commented Nov 20, 2015 at 15:02

1 Answer 1

3

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

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

filter_var(YOUR_POSTDATA, FILTER_VALIDATE_BOOLEAN);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.