Can't store output of jq in variable - json

I have some text that I want to escape to something I can use in JSON.
I can escape the text using jq and display it
normaltext="My normal text that I want to put in \"JSON\""
echo $normaltext | jq --slurp --raw-input
"My normal text that I want to put in \"JSON\"\n"
However, store that command output into a variable, jq doesn't seem to receive the input and just displays the help text.
escapedtext=$(echo $normaltext | jq --slurp --raw-input)
jq - commandline JSON processor [version 1.5-1-a5b5cbe]
Usage: jq [options] [file...]

Your version of jq evidently requires the . filter here, as in:
jq -s -R .

Related

Transform file content into json string with jq doesn't work in command substitution

This is working as expected:
$ cat /etc/tfe-config/sources/fluent-bit.conf.tpl | jq -R -s
$ "[OUTPUT]\n Name cloudwatch_logs\n Match *\n region eu-central-1\n log_group_name TFE-LogForwarding\n log_stream_name TFE-AllLogs"
However, assignment to a variable does not work:
$ MY_VARIABLE=$(cat /etc/tfe-config/sources/fluent-bit.conf.tpl | jq -R -s)
$ echo $MY_VARIABLE
jq - commandline JSON processor [version 1.5]
Usage: jq [options] <jq filter> [file...]
jq is a tool for processing JSON inputs, applying the
given filter to its JSON text inputs and producing the
filter's results as JSON on standard output.
The simplest filter is ., which is the identity filter,
copying jq's input to its output unmodified (except for
formatting).
For more advanced filters see the jq(1) manpage ("man jq")
and/or https://stedolan.github.io/jq
Some of the options include:
-c compact instead of pretty-printed output;
.... trimmed
I am on AWS EC2 machine with the latest Amazon Linux 2 image.
What is going on here?
The file looks like this:
[OUTPUT]
Name cloudwatch_logs
Match *
region eu-central-1
log_group_name TFE-LogForwarding
log_stream_name TFE-AllLogs
Two things:
You have to specify a filter for jq – just . to get the entire input
Once in a variable with whitespace, you must quote the string, else it shows up differently when you print it
var=$(cat /etc/tfe-config/sources/fluent-bit.conf.tpl | jq -R -s '.')
echo "$var"
Relevant Q&A:
How to use `jq` in a shell pipeline? (and also this GitHub issue)
I just assigned a variable, but echo $variable shows something else

Split multiple input JSONs with jq

Given a JSON line
{"a":0,"b":{"c":"C"}}{"x":33}{"asd":889}
of 3 independent JSON objects.
And need to handle then one by one. It would be nice to have something like
echo "$json" | jq --first-one
Expected output:
{"a":0,"b":{"c":"C"}}
I found the only command which can remove first object and output others. inputs
echo '{"a":0,"b":{"c":"C"}}{"x":33}{"asd":889}' | jq -c inputs
output:
{"x":33}
{"asd":889}
How to read only first object from input stream and do not touch the rest objects?
Workaround
While writing this Q I found a workaround, but it looks cumbersome
echo '{"a":0,"b":{"c":"C"}}{"x":33}{"asd":889}' | jq -c . | head -1
simply get first line...
Slurping should, in general, be avoided if possible. If your jq has input, you could simply write:
echo '{"a":0,"b":{"c":"C"}}{"x":33}{"asd":889}' |
jq -n input
If your jq does not have input, now would be a great time to upgrade to jq 1.6. If that is not an option, then by all means use the -s option, e.g. jq -s '.[0]'

Using jq to convert JSON {"k1":"v1","k2":"v2"} into CSV: v1,v2

I have a JSON file in.txt with lines like {"k1":"v1","k2":"v2"} and I want to create from it a CSV file out.txt with lines v1,v2. The JSON file may contain more than 10 key/value pairs, so I prefer a solution that doesn't require specifying each key in the input command.
So far I found this command:
jq -r '[.[]] | #csv' in.txt > out.txt
which produces output file with lines: "v1","v2". How can I get rid of double quotes?
update: I can remove double quotes using sed as following, but I'm still interested to find a solution using jq:
jq -r '[.[]] | #csv' in.txt | sed -e 's/\"//g' > out.txt
If you are sure that the input data does not contain a , you can use join(",").
Let's say you have this input file:
{"k1":"v1","k2":"v2"}
{"k1":"v3","k2":"v4"}
{"k1":"v5","k2":"v6"}
You can use join like this:
jq -r 'values|join(",")' input.file
Output:
v1,v2
v3,v4
v5,v6

How to parse JSON from stdin at Native Messaging host?

Utilizing the code at How do I use a shell-script as Chrome Native Messaging host application as a template and given the file file.json which contains
{"text":"abc"}
following the code at Iterate over json with jq and the jq documentation
$ cat file.json | jq --raw-output '.text'
outputs
abc
Am not certain how to incorporate the pattern at this Answer
while read -r id name date; do
echo "Do whatever with ${id} ${name} ${date}"
done< <(api-producing-json | jq --raw-output '.newList[] | "\(.id) \(.name) \(.create.date)"')
into the template at the former Answer for the purpose of capturing the single property "text" (abc) from the JSON within the loop using jq for the ability to pass that text to another system call then printf the message to client.
What we are trying to achieve is
json=$(<bash program> <captured JSON property>)
message='{"message": "'$json'"}'
where the {"text":"abc"} is sent to the Native Messaging host from client (Chromium app).
How to use jq within the code at the former Answer to get the JSON property as a variable?
Assuming that file.json contains the JSON as indicated, I believe all you will need is:
json=$(jq '{message: .}' file.json)
If you then echo "$json", the result will be:
{
"message": {
"text": "abc"
}
}

Ignore Unparseable JSON with jq

I'm using jq to parse some of my logs, but some of the log lines can't be parsed for various reasons. Is there a way to have jq ignore those lines? I can't seem to find a solution. I tried to use the --seq argument that was recommended by some people, but --seq ignores all the lines in my file.
Assuming that each log entry is exactly one line, you can use the -R or --raw-input option to tell jq to leave the lines unparsed, after which you can prepend fromjson? | to your filter to make jq try to parse each line as JSON and throw away the ones that error.
I have log stream where some messages are in json format.
I want to pipe the json messages through jq, and just echo the rest.
The json messages are on a single line.
Solution: use grep and tee to split the lines in two streams, those starting with "^{" pipe through jq and the rest just echo to terminal.
kubectl logs -f web-svjkn | tee >(grep -v "^{") | grep "^{" | jq .
or
cat logs | tee >(grep -v "^{") | grep "^{" | jq .
Explanation:
tee generates 2nd stream, and grep -v prints non json info, 2nd grep only pipes what looks like json opening bracket to jq.
This is an old thread, but here's another solution fully in jq. This allows you to both process proper json lines and also print out non-json lines.
jq -R . as $line | try (fromjson | <further processing for proper json lines>) catch $line'
There are several Q&As on the FAQ page dealing with the topic of "invalid JSON", but see in particular the Q:
Is there a way to have jq keep going after it hits an error in the input file?
In particular, this shows how to use --seq.
However, from the the sparse details you've given (SO recommends a minimal example be given), it would seem it might be better simply to use inputs. The idea is to process one JSON entity at a time, using "try/catch", e.g.
def handle: inputs | [., "length is \(length)"] ;
def process: try handle catch ("Failed", process) ;
process
Don't forget to use the -n option when invoking jq.
See also Processing not-quite-valid JSON.
If JSON in curly braces {}:
grep -Pzo '\{(?>[^\{\}]|(?R))*\}' | jq 'objects'
If JSON in square brackets []:
grep -Pzo '\[(?>[^\[\]]|(?R))*\]' | jq 'arrays'
This works if there are no []{} in non-JSON lines.