I have a JSON data structure the looks like this"
{
"cells": [
{
"source": [
"# Get the files in a directory n",
"ls -l n"
]
},
{
"source": [
"# Get the working directory n",
"pwd n"
]
},
{
"source": [
"# Get the network config n",
"ipconfig n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Bash",
"language": "bash",
"name": "bash"
}
}
}
I want to create a new structure from it that looks like this:
{
"source": [
"# Get the files in a directory n",
"ls -l n"
],
"title": "# Get the files in a directory n"
}
{
"source": [
"# Get the files in a directory n",
"ls -l n"
],
"title": "# Get the working directory n"
}
{
"source": [
"# Get the files in a directory n",
"ls -l n"
],
"title": "# Get the network config n"
}
My jq command looks like this:
cat test.json | jq '{source: .cells[].source, title: .cells[].source[0] }'
However I’m getting duplicate records in the output. I know it has something to do with the way that jq is processing the input data. Is there a way handle this scenario ?
2
Answers
On the one hand, it looks like you want:
On the other hand, the sample input shown in the Q does not seem to match up with the sample output.
Or, in accordance with your comment:
You want to iterate your
cells
array only once. You have at least 3 options that will all produce the same output:Assignment operator
=
See peak’s answer
It will assign the first item in
.source
to the (new) property.title
of each cellMerging objects
+
Construct a new object by merging in a new object with a single property into the existing cell:
This is useful if you want to add several new properties
Reconstructing result objects from scratch
{}
Since your objects only contains a single property, you can reconstruct the result object from scratch, listing all old and new properties:
Useful if the result structure does not resemble the input structure or uses only a few properties of the input.
The output for all 3 programs is: