Generating a JSON document from a collection of text files

I have a question about JSON files and bash scripting:

My goal is to create a JSON file that contains two keys, "key1" and "key2", each with multiple values stored in separate .txt files. The contents of the .txt files for each key are structured like this:

key1.txt:
val1
val2
val3
..

The structure of key2.txt is similar. Ultimately, I want the JSON file to look like this:

{
    key1:
    [ "val1"
      "val2"
       ...
    ]

    key2:
    [ "val1"
      "val2"
       ...
    ]
}

Does anyone know how to achieve this using bash scripting? Your help would be greatly appreciated!

Answer №1

Give this a try

#!/bin/bash
json="{"
for file in <directory path>/*.txt
do
filename=$(basename "$file")
filename="${filename%.*}"  
json=$json'"'$filename'"'": ["
while IFS= read -r line; do
echo $filename
json=$json'"'$line'",'
done < $file  
json="${json%?}"
json=$json"],"
done
json="${json%?}"
json=$json"}"
echo $json

Answer №2

To read in multiple files using jq, you can utilize the --slurpfile option. However, it is crucial that these files are formatted as actual JSON files. If your files do not meet this criteria, they will need to be converted first.

$ jq -R '.' key1.txt > /tmp/key1.json && \
  jq -R '.' key2.txt > /tmp/key2.json && \
  jq --slurpfile key1 /tmp/key1.json \
     --slurpfile key2 /tmp/key2.json \
     -n '{ key1: $key1, key2: $key2 }'

Alternatively, if you prefer to avoid working with temporary files, you have the option to create the JSON arrays within a subshell and pass them in using --argjson.

$ jq --argjson key1 "$(jq -R '.' key1.txt | jq -s '.')" \
     --argjson key2 "$(jq -R '.' key2.txt | jq -s '.')" \
     -n '{ key1: $key1, key2: $key2 }'

Answer №3

Generate an array of entries using a loop and then combine the loop output with a final jq invocation.

for file in *.txt; do
  <"$file" jq -nR --arg key "${file%.txt}" '{$key,value:[inputs]}';
done | jq -s 'from_entries'

Please note that this question and answer are closely related to How to update a json file by the contents read from other files using jq? and Construct JSON through jq tool in shell script loop.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the reason for requiring this to be passed as an Array instead of a String?

I'm currently learning node.js through a tutorial in a book titled Node Web Developments. Issue: I am struggling with understanding why an array [] is being passed as the 3rd argument from mult-node.js to the required function htutil.page(), instead ...

What is the process for parsing a JSON file (array format) with the simple JSON library?

Here is a code snippet I found on StackOverFlow that I attempted to use: JSONArray a = (JSONArray) parser.parse(new FileReader("c:\\exer4-courses.json")); Unfortunately, this line of code resulted in the following exception: java.lang.ClassCas ...

Learn how to extract the first occurrence of repeated data fields by parsing JSON using the org.JSON library in Java

I need help extracting the initial occurrence of "actualEPS" from this JSON file: {"symbol":"AAPL","earnings":[{"actualEPS":2.34,"consensusEPS":2.17,"estimatedEPS":2.17,"announceTime":"AMC","numberOfEstimates":10,"EPSSurpriseDollar":0.17,"EPSReportDate ...

"Enhancing JqGrid functionality with inline editing and custom formatters

I'm currently working with a column model that looks like this: { name: 'CostShare', index: 'CostShare', width: 50, formatter: 'number', formatoptions: { decimalPlaces: 2, suffix: "%" }, resizeable: true, align: 'ce ...

Exploring how Java can parse and read JSON using the Jackson library, specifically

I am working with a JSON file that contains an array and I have successfully extracted the data. However, I am struggling to figure out how to print out all the values within the array. Although I can manually select a specific element (like the 3rd car in ...

tips on locating the next immediate downloadable cell in a table

My table includes cells with colspan and rowspan attributes. <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <table border=1 id="mytable" > <tr><td>A1</td> <td> A2 < ...

Retrieve JSON data within an HTML element, where the element is sourced from an AJAX GET response

What is the best way to extract JSON data from the response below? $.get('http://localhost:8000/json', function(response) { alert(response); }); The response is as follows: <div id="dom-target" style="display: none;"> {"logo":"log ...

Tips for avoiding background color interference with raycaster

In my current three js scene, I have a ground, sky, and various objects. I want specific objects to change color to red when the mouse hovers over them, but not all objects should do this. Currently, everything I touch turns red, which is not what I want. ...

javascript onload button is selected

I am looking to create a button on page load for my login page in Chrome. I want the login button to be preselected when the page loads, and when I press Enter, the onclick function of the button should be triggered. Any advice on how to achieve this? Th ...

Tips on toggling between slides with Bootstrap Carousel

I am in the process of designing a portfolio website and have encountered a challenge. I want to divide it into two sections - a brief introduction and a carousel for showcasing projects. While I have managed to set up both sections, I'm facing an iss ...

To prevent the need for redundant iterations, arrange an object based on a specific field

Looking for a way to avoid repeating the same loop multiple times while sorting an object efficiently. Take a look at this sample object: movies = [ { title: "The Lord of the Rings: The Fellowship of the Ring" year: 2001 ...

Using TypeScript, pass an image as a prop in a Styled Component

I am facing an issue with the code below that is supposed to display the "NoBillsLaptopPNG.src" image on the screen, but for some reason, the image is not showing up. The images are being imported correctly, so I'm unsure why the image is not appeari ...

Is there a way to hide a paragraph or div using javascript?

I am experimenting with using buttons to hide paragraphs using javascript, but even when I set them as "hidden", there is still excess blank space left behind. Is there a way I can eliminate that extra space? Below is the javascript code: function backgro ...

I'm having trouble locating the corresponding end tag for "<%". How can I resolve this issue?

Here lies the issue: <% for(let i = 0; i < <%= elements %>.length; i++){ %> <li><%= elements[i] %></li> <%}%> ...

Apply express middleware to all routes except for those starting with /api/v1

Is it possible to define a catchall route like this? app.get(/^((?!\/api/v1\/).)*$/, (req, res) => { res.sendFile(path.join(__dirname, '../client/build', 'index.html'));}); ...

Show segments of video stream on page using node.js

I am currently exploring Node.js and trying to understand how streams work, so please bear with me if I seem a bit unclear. After reading some beginner notes on streams, I decided to test it out. In my project files, specifically in public/images/videos/S ...

Unable to extract the 'id' property from 'params' object in Next.js 13.4 due to its undefined value

I am currently trying to retrieve the [id] URL parameter in Next.js 13.4, but I keep encountering an error stating that params is undefined. Despite extensive online research and seeking assistance from ChatGPT, all I could find were examples for older ve ...

Is there a way to locate child components without needing to designate the higher-order component encompassing them?

When working with Material-ui, I often find that its extensible nature can be a hindrance when it comes to testing. For example, even if I am using the following code: const MyEventButton = () => (<IconButton /> <Event /> </IconButton ...

The Runtime Error encountered in NEXTJS: TypeError - Unable to iterate over 'games' as it is not

Attempting to create my inaugural website that showcases data from an API sans a tutorial. Does it seem like I may have overlooked something? I've successfully fetched the API and confirmed in the console log that the necessary data is present. Howev ...

What steps can be taken to resolve the "npm ERR! code ELIFECYCLE" error in a React application?

After attempting to start my React app with npm start, an error occurred : $ npm start > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4f3b3d2a212b3c0f7f617e617f">[email protected]</a> start C:\Users&bso ...