Home > OS >  Is it possible to pretty print JSON or array output from a device accessed by telnet?
Is it possible to pretty print JSON or array output from a device accessed by telnet?

Time:10-13

At work we use telnet to directly connect to embedded devices on our network to issue REST API calls to the device during testing and setup. We later use those calls when developing a web interface.

I like my history and cursor control in the shell, so I use rlwrap with telnet and that works great.

One personally annoying thing is that when I do an API call, like a GET, I 'get' back the data I want in a raw single-line format.

Example:

GET /tw/info
{"result":{"fault":0,"cps":2,"currentLoad":5,"lineVoltage":42176,"temperature":39,"voltage":42524,"current":53,"state":2}}

This is fine for short outputs, but when it gets to be 5-6 lines long or more it would be nice to have it pretty-printed for readability's sake.

Nothing fancy, just basic indenting would do, like:

GET /tw/info
{
  "result": 
  {
    "fault":0,
    "cps":2,
    "currentLoad":5,
    "lineVoltage":42176,
    "temperature":39,
    "voltage":42524,
    "current":53,
    "state":2
  }
}

Are there any known tricks, options, or plugins for telnet/rlwrap to achieve this? Or perhaps I missed a specialized telnet client somewhere? Or will I need to go the software-route and do something like use python and readline to suck out the output and format it in the host shell?

Any tips or hints to point me in the right direction are appreciated.

CodePudding user response:

There are many tools to format and pretty-print JSON. One such tool is with many questions and answers here on StackOverflow.

It consumes one or more JSON documents via stdin and formats those according to a filter. The simplest filter is . and recent jq versions will default to this filter if none is specified.

program | ./jq '.'

Note that GET /path/file is not a valid REST GET request, because it is missing the protocol version (HTTP/1.x) and the Host header for version 1.1.

For how to link this to an interactive telnet session: I don't know. Python is probably a sensible route as you have already suggested.

CodePudding user response:

So exclude first line when passing to jq.

program | { read line; echo "$line"; jq '.'; }
  • Related