Hacker News new | past | comments | ask | show | jobs | submit login
Show HN: JSON Pizza – Beautify your JSON quickly (json.pizza)
112 points by giveWatermelon 76 days ago | hide | past | web | favorite | 78 comments

OS X includes the json_pp command, so I often just do this to format JSON in my clipboard:

   pbpaste | json_pp | pbcopy
For just viewing, I like Node's console.dir() formatting better since it's more compact and colored (but it's unquoted JS objects, not JSON), so I aliased this command in my shell:

   json='node -e '\''console.dir(JSON.parse(fs.readFileSync("/dev/stdin", "utf-8")), { depth: null })'\'
Then I can do

   pbpaste | json

If you have `jq` installed then you can just pipe any JSON to `jq` and it will beautify and colorize it automatically.

  pbpaste | jq

+1 for JQ, I use it in just about any place I can

One of my absolute musts in a text editor is a feature that prompts for a command, pipes the selected text into it and replaces it with the command's output (for Visual Studio Code it comes as a plugin). So "Ctrl+A, Ctrl+\, 'json_pp', Enter" and voila, formatted JSON in my editor (Ctrl+\ is what the command is bound to). Also works great with grep, sort, awk...

Which VSCode plugin are you using for this? I’m not sure what to search to find it but it sounds handy :)

My favourite hack is that jf you have a python installation (common on most Linux/Mac environments), you likely can use `python -mjson.tool` https://www.jvt.me/posts/2017/06/05/pretty-printing-json-cli...

But I've also written about how to do it with various stacks for various things at https://www.jvt.me/tags/pretty-print/


    cat foo.json | python3 -m json.tool
Prettifying is also built in to python3 on any system.


    jq  . foo.json

jq is freaking awesome! It can do amazing stuff, it's like awk for JSON on steroids. Highly recommend reading the documentation: https://stedolan.github.io/jq/manual/

useless use of cat:

python3 -m json.tool foo.json

Usually though what happens is this:

    :) cat foo.json
    [oh crap]
    :) cat foo.json | python -m foo.tool
For the 2nd command I'd hit "[up] | pyth[tab] -m json.tool"

Not to threadcrap, but I am curious what people think about this.

Over the years I've seen a lot of developers take none open-source code, or private JSON data strings and paste them into random sites they find searching "json format" on google.

Does that make anyone else cringe? Is there anything we can do about this? Or is this just not a big deal and I shouldn't worry.

I had a junior dev show me a neat site where you can paste in a Java thread dump and it performs an analysis. After explaining why it's a bad practice to send diagnostic details to an un-trusted third party I think he understood, but it seems like every week I'm finding people using ngrok, unauthorized password managers, grammarly, JWT parsers, Base64 encoders, and all manner of questionable tools.

I too wonder if I'm out of touch, if I'm tilting at windmills.

> I'm finding people using ngrok... and all manner of questionable tools.

At least ngrok supports end-to-end TLS tunnels[0], where you use your own TLS key/certs and the ngrok server never sees plaintext (the ngrok client is also open source, so for the truly paranoid you can examine it to ensure it isn't doing anything nefarious).

But I agree... I've seen people at a company where I used to work pasting sensitive data into a public pastebin. It still hurts my brain to think about it.

[0] https://ngrok.com/docs#tls

You're not out of touch. People like to trade security for convenience and while it doesn't always present an issue, it's a bad habit to get into. It's also one thing to take personal risks, it's another to put risks onto the company.

How are any of those questionable tools?

Sure, don't put arbitrary shit on the internet and know where your data is going. But every example you gave is incredibly useful to many people on a daily basis.

Leaking a bit of code will unlikely cause a problem, but the guns that can backfire are some of the cert checkers and SAML validators.

It can also happen you don’t care about the data you are sharing. Why not using an online then?

Still too dangerous, and I don't trust new developers to make that determination. Once you get into the habit of pasting development details into random website textboxes hosted who-knows-where with who-knows-what ad networks, you're one keystroke away from leaking sensitive details that are correlated to your employer's IP range.

Or maybe I'm a crank and need to lighten up. That's why I'm asking.

It's a reasonable thing to worry about. Bad actors exist. IP is valuable. Computers are insecure. People are lazy. You have to be careful out there.

> I don't trust new developers to make that determination.

Ignoring this issue is a sign of professional immaturity. Recommend you view it as an opportunity to educate the younger members of your team. Show them the power of a solid CLI toolbox that respects your privacy while delivering solid performance.

Still, you shouldn't be dogmatic about it. Webapp tools can be useful for understanding a new programming language or API. Just be judicious.

I agree 100%, perhaps I could have phrased that better. I try to use it as a teachable moment: "Hey, instead of using base64decode.org did you know you could use atob and btoa in a web inspector?"

Security-related scanners are a tough one though. Free XSS scanners, free TLS cert checkers: The best intentions can result in unintended disclosure. Developers have it constantly beaten into their head "Security! Security! Security!" and are often given nothing more than an OWASP cheat-sheet, so I can totally understand and empathize with the thought process that leads someone to plug a company URL into a free web-hosted XSS scanner.

Hum. I can see both cases. I would also think even if they copy/paste sensitive information. Like SSNs or password. It will be so diluted in the noise of other people data that it won't matter. Most of these websites - I made one myself - are run by people like us and we won't care about what it sent to the server.

Google offers a digital leak prevention service as part of GCP. You could use it for offensive security to find likely PII without much concern about the noise.

Google runs this (or an internal version) of this service to make sure people serving third party ads aren't sending sensitive data. At one of my past companies our customers would send out email marketing campaigns that contained URLs with tracking parameters with PII. We wound up having to just strip off any query parameters we didn't explicitly need because Google kept flagging us for PII leaks caused by our customers.

So yeah, there's a lot of noise. But, people are listening out there!

You can do the same in the browser console. I don't really get why people need an online tool for this:

   copy(JSON.stringify(obj, null, 2))
obj can be parsed with JSON.parse if it is in text.

Even better, just open the JSON file in Firefox.

Not bad. I usually copy json data from the browser console, but for files this can be useful.

> I don't really get why people need an online tool for this:

That’s rather condescending, and probably not true. Surely you must be able to think of reasons why someone would use a website instead of writing a one-line program.

The only reason I can think of is if this is something which one very rarely needs. Otherwise, I'd think those who regularly handle JSON files are able to write a one line program.

And the JS console was only an example. Other languages can also pretty print JSON trivially. E.g. python.

On chrome at least copy(Paste json here) is enough

It drives me crazy when I see people do it. For the most part tools like VSCode have plugins for it as well, so no need to send this stuff to random third party.

The biggest struggle for me is diffing random bits of text. Pulling two JSON docs from the DB and wanting to compare them. Recently found a VSCode plugin that makes it a bit better, but still a pain in the ass.

Does a diffing tool maybe satisfy your requirements? I personally use Meld but there's lots of them out there.

I've caught coworkers doing this with base64 for at least a decade before JSON was a thing. And keep in mind we base64 things like credentials, RSA keys...

There are some things you just shouldn't paste into the internet.

This is what keeps our security industry employed. Anything like a pastebin is blocked at my workplace.

It should be noted that this particular site works without sending any data back to the server.

Aside from that, this is one area where web-based applications excel: You can inspect and limit what data an application is sending away about you via your browsers built-in dev tools and extensions like uMatrix (or your own request-filtering extensions).

I always quickly check my Chrome Inspector to make sure it's not sending anything to a server.

Don't count on this. There are ways to guess if the dev tools are likely to be open and then alter nefarious behavior based on that.

For example you can detect changes in window sizes or look for plugins that are in the global namespace (e.g. Redux Dev Tools). Better play it safe and don't copy and paste private data to random sites.

Another attack vector would be to avoid sending down any data unless it contains something that looks like a hash or a token, or has a keyword like "password."

There are also ways to wait until you close or navigate away from the page, using window.onbeforeunload / window.onunload / navigator.sendBeacon: https://stackoverflow.com/questions/4945932/window-onbeforeu...

Feedback: First time through I just pasted some JSON and wondered why it didn't format. I hadn't realised the page had instructions on it – I had assumed it was just sample JSON.

Second time through, I read the instructions, and realised that the keyboard shortcuts are Control-based – this is less common for macOS, "Cmd+Enter" feels like a more consistent shortcut to use.

I think this should probably just auto-format all the time. It's only for formatting, so that wouldn't get in the way.

CTRL for the shortcuts overlaps with the browser. You need to either completely take this over, or completely leave it be, and in this case, probably the latter. Otherwise I get shocked when I hit CTRL-w to see if it erases a word and it closes my window without warning.

There's also apparently some other things going on; CTRL-u uppercases the word you're on. A link to more docs or something may be helpful.

Do what https://prettier.io/playground/ does and have two windows so one autoformats.

I second this, I too expected this to auto-format - the only purpose of this tool is to prettify the JSON and rarely would anyone paste and then edit there.

Interestingly, some of the macOS shortcuts work but not others. I can kill text, for example, but yanking it back doesn't seem to work.

Non web based approach using jq (https://stedolan.github.io/jq/):

    json_source_on_stdout | jq .

Or on macOS, to quickly format the contents of your clipboard:

    pbpaste | jq . | pbcopy
Pretty sure this is one of my most frequent commands.

You can use Automator to create a service with a shell script action; just pick Quick Action, the rest should be pretty obvious.

Not so obvious to me ! I have created the Quick Action but I don't know how to trigger it, so I have saved it as an app. Also when I execute it from Automator (play button), the script doesn't work (nothing is pasted). Would you mind helping ? Looks the best way to quickly format a copied json ! Thanks

Yeah, that was a very terse explanation, and Automator is so user-friendly it's hard to use.

1. Start Automator.

2. In the "Choose a type..." sheet, choose "Quick Action".

3. Set these:

     Workflow recieves "current text" in "any application".
     Input is "entire selection". [X] Output replaces text.
4. Add "Run shell script" and select your preferred shell.

     jq .
(Note that Automator is handling your stdin / stdout.)

5. File / Save.

You can now find your workflow by command-clicking the document name in the window's titlebar. It should be in /Users/You/Library/Services

Now, fire up TextEdit, enter some JSON. Right-click, select Services and your service should be present. It's also in the TextEdit menu under Services.

Python also has one built in.

cat input.json | python3 -m json.tool

I want to like jq, and for doing a simple lookup it's great, but I find when I try to do something complicated the syntax just doesn't click.

I know, right? I've switched to using jp: its syntax is based on an actual standard and it clicks much more with me than jq's syntax.


Playing with `jp` a bit, I still like it, but it's very frustrating to do updates in place.

For example, I wanted to write a simple expression to delete outputs from an ipython notebook.

        "cells": [{
            "stuff": "blah blah",
            "outputs": ["crap", "to", "delete"]
        }], "other stuff": "blah blah"
The simplest expression I could come up with was:

    merge(@, {
      "cells": map(
        &merge(@, {"outputs": `[]`}),
And that's verbose because you're reconstructing the structure.

In fairness, it's impressive that the language can express it at all, given it's a query language.

Maybe the real answer is to denote a subset of JMESPath that is guaranteed to return assignable nodes, that is only selects, slices, filters, etc. Then you run the query and perform assignments against those.

Nice! I didn’t actually realise JMESPath was a standard, I first came across it in the AWS CLI and definitely found it nicer than jq. Good to avoid trying to learn both.

Thanks for this suggestion. I too also have problems dealing with jq syntax. jp looks a lot more intuitive.

You can go even simpler

  json_source_on_stdout | jq
If you give `jq` no arguments it acts like `jq .`

I think it might be useful to note for other readers here that jq is very powerful for parsing json - you can programatically search, select, map, and mutate parts of any json. If you work with a lot of json, it's worth checking out.

OS X has the Perl-based `json_pp` built in too.

A privacy policy (even though its open source and one can go look up the code) would help alleviate user concerns adopting this.

I agree! I am a bit worried to put any JSON in it just yet.

Cool looking interface. Are you monetizing in any way? I've been using https://jsonformatter.org/ for quite some time and have gotten used to their features (minifying & beautifying) but it's ad-based.


  const formattedText = JSON.stringify(JSON.parse(text), null, 2)`

It's converting numbers to floats and deleting additional precision.

There are a few features that can cut out a ton of unnecessary whitespace, like keeping short lists and maps on a single line, and keeping singleton list brackets tight.

Nice - i've been a long time fan of https://jsoneditoronline.org/ which has some nice sort/filter functions built in.

You can also just open chrome / firefox dev tools console and assign it to a variable...

Sadly, all of these tools fall over for very large json objects

Nice job! Excuse me for plugging my own project that does more or less the same: http://www.inspectjson.com/. 100% clientside, so no sharing but also no snooping :-)

I made a command line one kind of like this: https://www.npmjs.com/package/color-json-cli

I've been using http://zaa.ch/jsonlint/ for a while. Does validation and formatting. All in browser.

I made a thing and you can read the source: https://github.com/carlmjohnson/json-tidy

When pizza was mentioned I thought "pie chart" and was therefore assuming an automatic chart generator that would auto-visualize an arbitrary structure. Anyone know a tool like that?

bug in cursor rendering: https://imgur.com/a/imGJCRC (chrome 75.0.3770.142, ubuntu 16.04)

Looks nice and simple :)

I think a strong example would really help your case, the landing page now has already formatted json, and I can't figure out where to get a messy example from quickly.

I like it! It's alot nicer than my json formatter https://oil-comma.glitch.me/

I couldn't get the Ctrl-L thing to work. (on a mac/chrome)

Ctrl-B works.

Is the .pizza just for fun or am I missing a reference?

Its because pies start out as unorganized messes and end up as a pizza.

Also for fun

This is actually dope. I need to do this a lot and I hate doing it from command line because i usually am pasting huge blobs

Just a thought: add a shortcut to compress formatted JSON.

What's different to VScode `alt+shift+f` for .json?

This is neat. I will start using! thanks!

Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact