Home > Software design >  Can't convert string to boolean
Can't convert string to boolean

Time:03-09

I'm trying to parse an ini file using ini. However, I can't manage to convert my string value to a boolean and I think I'm going crazy!

I have tried the obvious variable = (value == 'true'); approach listed below:

    let myBool;
    for (const [key, value] of iniObject) {
        console.log(`pair: ${key} - ${value}`);
        if(key == 'testBool') {
            myBool = (value == 'true');
            console.log(`myBool set to ${myBool} (${typeof myBool}) - value: ${value}`);
        }
    }

Instead of setting myBool to true, it is set to false! The console.log() output is the following, showing that the input value is indeed "true":

    [1] pair: testBool - true
    [1] myBool set to false (boolean) - value: true

I have also tried the following without success:

    myBool = (JSON.parse(value) == 'true');
or
    myBool = (value == 'true') ? true : false;

The corresponding line in the ini is testBool=true, so nothing special. What am I missing? I feel like an idiot for having spent the last 3 hours on this, so I would really appreciate some help on this.

Thank you for your time!

CodePudding user response:

I don't know how the ini works, but did you check what is the type of value?

Maybe it has already parsed it as a boolean and that is why you get false when comparing?

"true" == true // false
  • Related