@magic-libraries/json

@magic-libraries/json

this is the @magic-libraries json library. it returns errors instead of throwing them and catches (some) malformed objects when stringifying.

installation

npm install @magic-libraries/json

usage

in a page/component, just use the lib.json functions

lib.json.stringify({ some: { object: ['with', 'values'] } })

renders

{ "some": { "object": ["with", "values"] } }

caveat

this library is intended to handle incoming web traffic. we can never be sure that this incoming packets will not include faulty json.

to use this library without checking it's return value your input json MUST be wellformed.

in all (other) cases the following pattern should be employed (and enhanced with custom error messages).

export const ViewStringify = unsafe => {  const result = lib.json.stringify(unsafe)  return div([result.message ? result.message : result])}export const ViewParse = unsafe => {  const result = lib.json.parse(unsafe)  // in this case we can not check for .message,  // since unsafe might have a .message key after parsing  div([result instanceof Error ? result.message : result])}

example modules

the example/assets directory contains two modules that use the lib.json functions:

<JsonStringify state></JsonStringify>

renders

stringified JSON:{  "state": {    "title": "@magic-libraries/json",    "description": "json client lib for @magic. returns errors instead of throwing them.",    "logotext": "@magic-libraries/json",    "menu": [      {        "to": "/json/#installation",        "text": "installation"      },      {        "to": "/json/#usage",        "text": "usage"      },      {        "to": "/json/#caveat",        "text": "caveat"      },      {        "to": "/json/#source",        "text": "source"      }    ],    "nospy": {      "show": false    },    "theme": "dark",    "pageClass": {},    "url": "/json/",    "root": "/json/",    "pages": {      "/json/": {        "menu": [          {            "to": "/json/#installation",            "text": "installation"          },          {            "to": "/json/#usage",            "text": "usage"          },          {            "to": "/json/#caveat",            "text": "caveat"          },          {            "to": "/json/#source",            "text": "source"          }        ]      },      "/json/404/": {        "title": "404 - not found",        "description": "404 - not found."      }    }  }}
<JsonParse>{ "valid": true }</JsonParse>

renders

parsed (and then stringified) JSON:{  "valid": true}

source

the source for this page is in the example directory and gets built and published to github using @magic/core