• JSON.stringify 函数 (JavaScript)


    将 JavaScript 值转换为 JavaScript 对象表示法 (Json) 字符串。

    JSON.stringify(value [, replacer] [, space])

    使用 JSON.stringify 将 contact 对象转换为 JSON 文本。 定义 memberfilter 数组以便只转换surname 和 phone 成员。 省略 firstname 成员。

    var contact = new Object();
    contact.firstname = "Jesper";
    contact.surname = "Aaberg";
    contact.phone = ["555-0100", "555-0120"];
    
    var memberfilter = new Array();
    memberfilter[0] = "surname";
    memberfilter[1] = "phone";
    var jsonText = JSON.stringify(contact, memberfilter, "	");
    document.write(jsonText);
    // Output:
    // { "surname": "Aaberg", "phone": [ "555-0100", "555-0120" ] }

    将 JSON.stringify 与一个数组一起使用。 replaceToUpper 函数将数组中的每个字符串转换为大写形式。

    var continents = new Array();
    continents[0] = "Europe";
    continents[1] = "Asia";
    continents[2] = "Australia";
    continents[3] = "Antarctica";
    continents[4] = "North America";
    continents[5] = "South America";
    continents[6] = "Africa";
    
    var jsonText = JSON.stringify(continents, replaceToUpper);
    
    function replaceToUpper(key, value) {
        return value.toString().toUpperCase();
    }
    
    //Output:
    // "EUROPE,ASIA,AUSTRALIA,ANTARCTICA,NORTH AMERICA,SOUTH AMERICA,AFRICA"

    使用 toJSON 方法将字符串值转换为大写形式。

    var contact = new Object();
    contact.firstname = "Jesper";
    contact.surname = "Aaberg";
    contact.phone = ["555-0100", "555-0120"];
    
    contact.toJSON = function(key)
     {
        var replacement = new Object();
        for (var val in this)
        {
            if (typeof (this[val]) === 'string')
                replacement[val] = this[val].toUpperCase();
            else
                replacement[val] = this[val]
        }
        return replacement;
    };
    
    var jsonText = JSON.stringify(contact);
    document.write(jsonText);
    
    // Output:
    {"firstname":"JESPER","surname":"AABERG","phone":["555-0100","555-0120"]}
    
    
    
    '{"firstname":"JESPER","surname":"AABERG","phone":["555-0100","555-0120"]}'
    */
  • 相关阅读:
    VUE-周日历的实现
    Mac电脑部分网页打不开怎么办
    python pytesseracct WinError2
    Windows Error的错误代码
    python pytesseract——3步识别验证码的识别入门
    python——pyinstaller踩的坑 UnicodeDecodeError
    python 处理excel踩过的坑——data_only,公式全部丢失
    Python3行代码之——截图工具
    python openpyxl内存不主动释放 ——关闭Excel工作簿后内存依旧(MemoryError)
    pywintypes.com_error: (-2147352567, '发生意外 解决方案
  • 原文地址:https://www.cnblogs.com/siyunianhua/p/4047832.html
Copyright © 2020-2023  润新知