Giter VIP home page Giter VIP logo

safe-json-parse-and-stringify's Introduction

safe-json-parse-and-stringify

Install

npm i safe-json-parse-and-stringify --save

Usage

import { jsonParse, jsonStringify, cloneDeep } from 'safe-json-parse-and-stringify';

Detail

jsonParse(parseStr, defaultValue)

use JSON.parse with try catch,if catch error, return defaultValue。

Params

  • {any} parseStr
  • {any} defaultValue

Returns

{any}

Examples

input first param output
jsonParse('[1,2,3]', []) string [1,2,3]
jsonParse([1,2,3],[]) not string [1,2,3]
jsonParse('{a:1}', {}) string {}
jsonParse({a:1}, {}) not string {a:1}
jsonParse("",{}) string {}
jsonParse("",[]) string []
jsonParse("") string undefined
jsonParse() undefined undefined

jsonStringify

Like JSON.stringify, but doesn't throw on circular references.

Params

Takes the same arguments as JSON.stringify.

var circularObj = {};
circularObj.circularRef = circularObj;
circularObj.list = [ circularObj, circularObj ];
console.log(jsonStringify(circularObj, null, 2));

Output:

{
  "circularRef": "[Circular]",
  "list": [
    "[Circular]",
    "[Circular]"
  ]
}

Details

The fourth argument usually not used

jsonStringify(obj, serializer, indent, decycler)

The first three arguments are the same as to JSON.stringify. The last is an argument that's only used when the object has been seen already.

The default decycler function returns the string '[Circular]'. If, for example, you pass in function(k,v){} (return nothing) then it will prune cycles. If you pass in function(k,v){ return {foo: 'bar'}}, then cyclical objects will always be represented as {"foo":"bar"} in the result.

cloneDeep

Using JSON.parse(JSON.stringify(obj)) for deep clone is unpredictable and not safe.Use cloneDeep instead.

Example

const a = {};
a.a = a;
const b = JSON.parse(JSON.stringify(a));
/*
Uncaught TypeError: Converting circular structure to JSON
    --> starting at object with constructor 'Object'
    --- property 'a' closes the circle
    at JSON.stringify (<anonymous>)
    at <anonymous>:3:27
*/

Details

This method is loosely based on the structured clone algorithm and supports cloning arrays, array buffers, booleans, date objects, maps, numbers, Object objects, regexes, sets, strings, symbols, and typed arrays. The own enumerable properties of arguments objects are cloned as plain objects. An empty object is returned for uncloneable values such as error objects, functions, DOM nodes, and WeakMaps. And it recursively clones value.

Arguments

value (*): The value to recursively clone.

Returns

(*): Returns the deep cloned value.

Example

var objects = [{ 'a': 1 }, { 'b': 2 }];

var deep = cloneDeep(objects);
console.log(deep[0] === objects[0]);
// => false

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.