The Power of the JSON.stringify() replacer parameter

As previously detailed (2013 😱), you can use JSON.stringify()‘s second replacer parameter to pluck specific fields from it, by passing in an array:

var person = {"name":"Jim Cowart","location":{"city":{"name":"Chattanooga","population":167674},"state":{"name":"Tennessee","abbreviation":"TN","population":6403000}},"company":"appendTo"};

JSON.stringify(person, ["name", "company"], 4);
// ~> "{
//      "name": "Jim Cowart",
//      "company": "appendTo"
// }"

As Pawel explains the parameter can also be a function, to manipulate data before it is being returned. This comes in handy if you want to stringify a Set, for example:

const dude = {
  name: "Pawel",
  friends: new Set(["Dan", "Pedro", "Mr Gregory"])
};

const dudeStringified = JSON.stringify(dude, (key, value) =>
  value instanceof Set ? [...value] : value
);

console.log(dudeStringified);
// ~> {"name":"Pawel","friends":["Dan","Pedro","Mr Gregory"]}

The Power of the JSON.stringify() replacer parameter →

💡 Here’s a practicalu use-case: If your data object holds sensitive data, you can use the replacer to filter that part out:

const user = {
  name: 'Bramus',
  password: 'Azerty123',
};

JSON.stringify(user, (key, value) =>
    (key === 'password') ? 'XXXXXXXXXXXX' : value
);
// ~> "{"name":"Bramus","password":"XXXXXXXXXXXX"}"

Faster JavaScript Apps with JSON.parse()

A performance trick that’s been doing rounds on Twitter, now available as a video:

Because the JSON grammar is much simpler than JavaScript’s grammar, JSON can be parsed more efficiently than JavaScript. This knowledge can be applied to improve start-up performance for web apps that ship large JSON-like configuration object literals (such as inline Redux stores).

So instead of assigning a JS object to your store, assign the output of JSON.parse('{…}') to it.

There’s also a Babel plugin named babel-plugin-object-to-json-parse available that can automatically adjust your code for you.

👍 Great to hear Mathias sport the biggest web caveat there is: “It Depends”

JSONbox – Free HTTP based JSON Storage

jsonbox.io lets you store, read & modify JSON data over HTTP APIs for free. Copy the URL below and start sending HTTP requests to play around with your data store.

Oh, this will come in handy for Workshops and quick Proof Of Concepts:

curl -X POST 'https://jsonbox.io/demobox_6d9e326c183fde7b' \
    -H 'content-type: application/json' \
    -d '{"name": "Jon Snow", "age": 25}'

// {"_id":"5d776a25fd6d3d6cb1d45c51","name":"Jon Snow","age":25,"_createdOn":"2019-09-10T09:17:25.607Z"}

Don’t know about the retention policy though 😉

jsonbox.io →

JSON5 – JSON for Humans

JSON isn’t the friendliest to write. Keys need to be quoted, objects and arrays can’t have trailing commas, and comments aren’t allowed — even though none of these are the case with regular JavaScript today.

JSON5 is a proposed extension to JSON that allows these kinds of things. Here’s an example showcasing most of its features:

{
    foo: 'bar',
    while: true,

    this: 'is a \
multi-line string',

    // this is an inline comment
    here: 'is another', // inline comment

    /* this is a block comment
       that continues on another line */

    hex: 0xDEADbeef,
    half: .5,
    delta: +10,
    to: Infinity,   // and beyond!

    finally: 'a trailing comma',
    oh: [
        "we shouldn't forget",
        'arrays can have',
        'trailing commas too',
    ],
}

Note that the JSON5 proposal is in no way official (technically a new MIMEType is required), and – I fear – most likely won’t get that much adoption/traction with things like YAML already floating around…

JSON5 JS Parser →
JSON5 PHP Parser →

JSON Feed

We — Manton Reece and Brent Simmons — have noticed that JSON has become the developers’ choice for APIs, and that developers will often go out of their way to avoid XML. JSON is simpler to read and write, and it’s less prone to bugs.

So we developed JSON Feed, a format similar to RSS and Atom but in JSON. It reflects the lessons learned from our years of work reading and publishing feeds.

The format itself is very easy to read/interpret:

{
    "version": "https://jsonfeed.org/version/1",
    "title": "My Example Feed",
    "home_page_url": "https://example.org/",
    "feed_url": "https://example.org/feed.json",
    "items": [
        {
            "id": "2",
            "content_text": "This is a second item.",
            "url": "https://example.org/second-item"
        },
        {
            "id": "1",
            "content_html": "<p>Hello, world!</p>",
            "url": "https://example.org/initial-post"
        }
    ]
}

A plugin for WordPress is also available.

Announcing JSON Feed →
JSON Feed Plugin for WordPress →

(via ★)

Jasonette – Build cross-platform mobile apps using JSON

Just like how web browsers turn HTML into a web page, Jasonette turns JSON into iOS native components. This lets you build native apps by writing a simple JSON.

Here’s a small snippet/example:

{
    "$jason": {
        "head": {
            "title": "{ ˃̵̑ᴥ˂̵̑}",
            "offline": "true",
            "actions": {
                "$foreground": {
                    "type": "$reload"
                },
                "$pull": {
                    "type": "$reload"
                }
            }
        },
        "body": {
            "header": {
                "style": {
                    "background": "#ffffff"
                }
            },
            "style": {
                "background": "#ffffff",
                "border": "none"
            },
            "sections": [
                {
                    "items": [
                        {
                            "type": "vertical",
                            "style": {
                                "padding": "30",
                                "spacing": "20",
                                "align": "center"
                            },
                            "components": [
                                {
                                    "type": "label",
                                    "text": "It's ALIVE!",
                                    "style": {
                                        "align": "center",
                                        "font": "Courier-Bold",
                                        "size": "18"
                                    }
                                }
                            ]
                        },
                        {
                            "type": "label",
                            "style": {
                                "align": "right",
                                "padding": "10",
                                "color": "#000000",
                                "font": "HelveticaNeue",
                                "size": "12"
                            },
                            "text": "Check out Live DEMO",
                            "href": {
                                "url": "http://www.jasonbase.com/things/xXQ"
                            }
                        },
                        {
                            "type": "label",
                            "style": {
                                "align": "right",
                                "padding": "10",
                                "color": "#000000",
                                "font": "HelveticaNeue",
                                "size": "12"
                            },
                            "text": "Watch the tutorial video",
                            "href": {
                                "url": "https://www.youtube.com/watch?v=S7yGejKIH6Q",
                                "view": "Web"
                            }
                        }
                    ]
                }
            ]
        }
    }
}

The JSON is fetched over HTTP, and then loaded into your app:

This declarative way of working reminds me of one of the approaches I took at work whilst building Culture Club Magazine. Next to the default Story Item types (Cover, Teaser, Article, List, etc.) – each with their specific properties – there’s also a story item type named Custom which accepts a declarative list of components (along with their style, animations, and actions). That list is then translated to actual React components which get rendered inside the story item itself 🙂

Jasonette →
Build cross-platform mobile apps using nothing more than a JSON markup →

DocJSON – JSON HyperMedia Documents

docjson

A DocJSON document consists of standard JSON with the addition of a set of hypermedia controls that are used to express the actions that may be taken. DocJSON is a flexible document format that does not impose any structural restrictions either on the data representation style or on the layout of hypermedia controls used within the document.

The true power of the spec lies in restrictions it oposes:

A document may be any valid JSON with the single restriction that the object key "_type" is reserved.

Real genius imho, as it allows the implementer to use any specific structure he wants instead of imposing a structure as other formats such as Collection+JSON, Siren, Hal, JSON-LD, etc. do.

If for one always inject the returned HTTP status code as a status object into the response (example). With DocJSON I’m allowed to do so, plus I can make my API discoverable by consumers who have no prior knowledge of the keys it holds.

Linking back to some HyperMedia things I’ve been tinkering about myself this might actually formulate the answer to the problem I had: wanting to roll my own structure without needing to register a new format (which one shouldn’t).

Looking forward to how this spec will evolve 🙂

DocJSON →

Related: JSON API →