json-loose
A utility to handle and transform loosely structured data into valid JSON strings. It offers an intuitive solution to ensure data consistency and compatibility, providing a safer alternative to using the Function
constructor to obtain an object from a string.
Install
You can install this module using npm or yarn:
npm i json-loose
yarn add json-loose
Usage
The jsonLoose
function takes an invalid JSON string as input and returns a JSON-like string representation of the transformed data.
import jsonLoose from 'json-loose'
const invalidJSON = `
{
name: 'Bambang Ekalaya',
username: "@palgunadi",
age: 30,
isStudent: true
}
`
const data = jsonLoose(invalidJSON)
console.log(data)
Yields:
{
"name": "Bambang Ekalaya",
"username": "@palgunadi",
"age": 30,
"isStudent": true
}
You can also specify an optional context object to transform Identifier values:
import jsonLoose from 'json-loose'
const invalidJSON = `
[
"foo",
true,
[1, 2, wife],
{
[n]: 'Bambang Ekalaya',
username: "@palgunadi",
age: 30,
address: [{city:city}, [country]],
skills: skills,
isStudent: true,
relation: {
wife: wife,
guru: guru,
[bar]: "qux"
},
},
],
`
const context = {
n: 'name',
skills: 'Archery',
city: 'Nishada',
country: 'Aravalli',
wife: 'Anggraini',
guru: 'Drona'
}
const data = jsonLoose(invalidJSON, context)
console.log(data)
Yields:
[
"foo",
true,
[1, 2, "Anggraini"],
{
"name": "Bambang Ekalaya",
"username": "@palgunadi",
"age": 30,
"address": [{ "city": "Nishada" }, ["Aravalli"]],
"skills": "Archery",
"isStudent": true,
"relation": { "wife": "Anggraini", "guru": "Drona", "bar": "qux" }
}
]
Related
- attributes-parser – A utility for parsing and tokenizing attributes string into meaningful tokens and key-value pairs.
Contributing
We 💛 issues.
When committing, please conform to the semantic-release commit standards. Please install commitizen
and the adapter globally, if you have not already.
npm i -g commitizen cz-conventional-changelog
Now you can use git cz
or just cz
instead of git commit
when committing. You can also use git-cz
, which is an alias for cz
.
git add . && git cz
License
A project by Stilearning © 2023.