text 来自p1的isJson

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了text 来自p1的isJson相关的知识,希望对你有一定的参考价值。

/**
 * Determine if a string is JSON
 * @param  {String}         string A string to test
 * @return {Boolean|Object}        If it is JSON, it will be parsed, otherwise it returns false
 */
export default function isJson(string) {

    try {

        const parsed = JSON.parse(string);

        // Eliminate the funny things JSON.parse is willing to handle that isn't JSON
        if (parsed && typeof parsed === 'object') {
            return parsed;
        }

    // Go gentle into that good night
    } catch (e) {} // eslint-disable-line no-empty

    return false;

}

import isJson from '../isJson';

describe('isJson', () => {

    it('should detect if a string is JSON by parsing it', () => {

        const json = JSON.stringify({
            mock: 'Rick',
            number: 1
        });

        const isJsonTest = isJson(json);

        expect(isJsonTest)
            .toMatchObject({
                mock: 'Rick',
                number: 1
            });
    });

    it('should properly handle a null type by returning false', () => {

        // JSON.stringify can be passed null successfully
        // This test should return false
        const isJsonTest = isJson(null);

        expect(isJsonTest)
            .toBeFalsy();
    });

    it('should properly handle a number type by returning false', () => {

        // JSON.stringify can be passed undefined successfully
        // This test should return false
        const isJsonTest = isJson(100);

        expect(isJsonTest)
            .toBeFalsy();
    });

    it('should properly handle a boolean type by returning false', () => {

        // JSON.stringify can be passed a boolean successfully
        // This test should return false
        const isJsonTest = isJson(true);

        expect(isJsonTest)
            .toBeFalsy();
    });

    it('should properly handle a string type by returning false', () => {

        // JSON.stringify can be passed a string successfully
        // This test should return false
        const isJsonTest = isJson('Rick and Morty');

        expect(isJsonTest)
            .toBeFalsy();
    });
});


以上是关于text 来自p1的isJson的主要内容,如果未能解决你的问题,请参考以下文章

javascript IsJson

javascript isJSON

如何将来自间接依赖项目的版本合并到一个项目中

警卫声明不一致

json.loads() 是不是容易受到任意代码执行的影响?

code#5 P1 报告