- Notifications
You must be signed in to change notification settings - Fork6
Parse and manipulate JSON5 strings
License
NotificationsYou must be signed in to change notification settings
Rich-Harris/golden-fleece
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Parse aJSON5 string (like JSON, but less strict).
For theSvelte REPL, where we want to allow arbitrary data in the bottom right-hand panel, but we also want to update the object without reformatting it as JSON.
Install it withnpm install golden-fleece
and import it into your app:
import*asfleecefrom'golden-fleece';
constast=fleece.parse(`true`);// { start: 0, end: 4, type: 'Literal', raw: 'true', value: true }
The returned AST isESTree compliant.
You can optionally pass callbacks that are fired whenever a value or comment is encountered:
constast=fleece.parse(str,{onComment:comment=>{console.log('got a comment',comment);},onValue:value=>{console.log('got a value',value);}});
const{ answer}=fleece.evaluate(`{ answer: 42 }`);answer===42;// true
This is where it gets fun:
conststr=`number: 1,string: 'yes',object: { nested: true },array: ['this', 'that', 'the other']`;constobject=fleece.evaluate(str);object.number=42;object.array[2]='EVERYTHING';fleece.patch(str,object)===`{number: 42,string: 'yes',object: { nested: true },array: ['this', 'that', 'EVERYTHING']}`;// true
Notice that the formatting has been preserved.
constobject={string:'hello','quoted-property':2,array:[3,4]};fleece.stringify(object)===`{string: "hello","quoted-property": 2,array: [3,4]}`;// true
To indent with spaces instead of tabs, passspaces: n
, wheren
is the number of spaces at each level of indentation.
fleece.stringify(object,{spaces:2})===`{ string: "hello", "quoted-property": 2, array: [ 3, 4 ]}`;// true
To prefer single-quotes to double-quotes, passsingleQuotes: true
:
fleece.stringify(object,{singleQuotes:true})===`{string: 'hello','quoted-property': 2,array: [3,4]}`;// true
About
Parse and manipulate JSON5 strings
Resources
License
Stars
Watchers
Forks
Packages0
No packages published