Parse-Json-Or
Safely parse JSON strings while explicitly indicating the behaviour in case of a parsing error
Getting Started
Just install the package (npm i parse-json-or --save
)
Prerequisites
No Prerequisites
Installing
- Just install the package
npm i parse-json-or --save
Use it in your code
Variables used in our examples :
// Require the packagelet parseJson = ; // We will use these values for our exampleslet demoObject = foo: 1 bar: 2 ;let validJsonString = JSON;let invalidJsonString = "a{}" ;
orValue(jsonString: string, orValue: *)
Parse JSON safely or get the 'orValue' in case of failure :
// Parse JSON safely or return the 'orValue'let value; value = parseJson; // value = { foo: 1, bar: 2 } value = parseJson; // value = "You can use any value from any type" value = parseJson; // value = 15 value = parseJson; // value = true value = parseJson; // value = { evenObjects: true }
orError(jsonString: string, errorBuilder: string)
Parse JSON safely or raise an error created with a message that is created from the given string in case of failure :
// Parse JSON safely or raise an error (created from a string) in case of failurelet errorBuilderString = "This is a string message";let value; value = parseJson; // value = { foo: 1, bar: 2} try value = parseJson; // error = "You can use value from any type"; catch err console; // "This is a string message"
orError(jsonString: string, errorBuilder: function)
Parse JSON safely or throw an error with a 'message' property that is the returned value from the passed function
// Parse JSON safely or raise an error (created from a string) in case of failurelet `:`; let value;value = parseJson; // value = { foo: 1, bar: 2} try value = parseJson; catch err console; // "SyntaxError: Unexpected token a in JSON at position 0:a{}";
orError(jsonString: string)
// In case that the no 'errorBuilder' is given, the default error message will be used.let value;value = parseJson; // value = { foo: 1, bar: 2} try value = parseJson; // error = z catch err console; // "SyntaxError: Unexpected token a in JSON at position 0"
Running the tests
npm run test
Built With
- lodash - A modern JavaScript utility library delivering modularity, performance and extras.
Contributing
We are open to your contribution.
Versioning
We use SemVer for versioning.
Authors
- Or Lavy - Initial work - OrLavy
License
This project is licensed under the MIT License - see the LICENSE.md file for details