Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert .txt to json using Shell scripting

Tags:

json

shell

jq

I have a text file data.txt:

Framework1,Version1
Framework2,Version2
Framework3,Version3

I need to convert it to data.json which would look like:

[
{"FrameworkName":"Framework1", "VersionName":"Version1"},
{"FrameworkName":"Framework3", "VersionName":"Version2"},
{"FrameworkName":"Framework3", "VersionName":"Version3"}
]

I have tried using awk but it hasn't helped me much. Any help would be appreciated.

like image 366
devops_engineer Avatar asked Mar 02 '18 10:03

devops_engineer


People also ask

How do I convert notepad to JSON?

In Notepad++ on the Language menu you will find the menu item - 'J' and under this menu item chose the language - JSON. Once you select the JSON language then you won't have to worry about how to save it. When you save it it will by default save it as . JSON file, you have to just select the location of the file.

Can I convert JSON to txt?

Users can also Convert JSON File to Text by uploading the file. Download converted file with txt extension. JSON to Text Online works well on Windows, MAC, Linux, Chrome, Firefox, Edge, and Safari.


1 Answers

jq solution:

jq -Rs '[ split("\n")[] | select(length > 0) 
          | split(",") | {FrameworkName: .[0], VersionName: .[1]} ]' data.txt

The output:

[
  {
    "FrameworkName": "Framework1",
    "VersionName": "Version1"
  },
  {
    "FrameworkName": "Framework2",
    "VersionName": "Version2"
  },
  {
    "FrameworkName": "Framework3",
    "VersionName": "Version3"
  }
]

https://stedolan.github.io/jq/manual/v1.5/

like image 84
RomanPerekhrest Avatar answered Sep 30 '22 10:09

RomanPerekhrest