【问题标题】:How to change JSON boolean to Yes or No with Javascript如何使用 Javascript 将 JSON 布尔值更改为 Yes 或 No
【发布时间】:2025-12-09 04:40:01
【问题描述】:

嘿,我是 javascript 新手。

我正在使用 API,但无法将 JSON 布尔值转换为 YES 或 NO。

布尔值在电话中默认为假。所以我试图将false返回为“NO”

这是我的代码:

        function loadCustomer(e) {
        const xhr = new XMLHttpRequest();

        xhr.open('GET', 'https://jsonplaceholder.typicode.com/todos/1', true);

        xhr.onload = function () {
            if (this.status === 200) {
                // console.log(this.responseText);

                const person = JSON.parse(this.responseText);


                const output = `
                    <ol>
                    <li>ID: ${person.userId}</li>
                    <li>Name: ${person.id}</li>
                    <li>Company: ${person.title}</li>
                    <li>Phone: ${person.completed}
                    </li>
                    </ol>
                `;

                document.getElementById('customer').innerHTML = output;
                // console.log(customer.completed);
                // if (customer.completed = false) {
                //     output.innerHTML = 'hey'
                // }

            }
        }

        xhr.send();
    }

这是 JSON:

{ “用户ID”:1, “身份证”:1, "title": "delectus aut autem", “完成”:假 }

【问题讨论】:

  • 使用双等号比较:if(customer.completed == false),否则,你赋值为 false。

标签: javascript api return boolean


【解决方案1】:

你可以试试这个:

<li>Phone: ${person.completed ? 'YES' : 'NO'}</li>

【讨论】:

    【解决方案2】:

    要显示“YES”或“NO”而不是真假,请尝试:

        function loadCustomer(e) {
        const xhr = new XMLHttpRequest();
    
        xhr.open('GET', 'https://jsonplaceholder.typicode.com/todos/1', true);
    
        xhr.onload = function () {
            if (this.status === 200) {
                // console.log(this.responseText);
    
                const person = JSON.parse(this.responseText);
    
                var phone = "NO";
                if (customer.completed) {
                    phone = "YES";
                }
                const output = `
                    <ol>
                    <li>ID: ${person.userId}</li>
                    <li>Name: ${person.id}</li>
                    <li>Company: ${person.title}</li>
                    <li>Phone: {PHONE}
                    </li>
                    </ol>
                `.replace(/{PHONE}/g, phone);
    
                document.getElementById('customer').innerHTML = output;
                // console.log(customer.completed);
                // if (customer.completed = false) {
                //     output.innerHTML = 'hey'
                // }
    
            }
        }
    
        xhr.send();
    }
    

    【讨论】: