Bash command to Read, Output and Manipulate JSON File


If you want to read and output the text from a JSON file, you can do that in many ways. Let's take a look at some of them.


Option 1: Using cat command

    # cat data.json
    
    {
      "city": "New York",
      "forecast": [
        { "date": "2023-08-18", "temp": 78 },
        { "date": "2023-08-19", "temp": 82 },
        { "date": "2023-08-20", "temp": 75 },
        { "date": "2023-08-21", "temp": 70 },
        { "date": "2023-08-22", "temp": 73 }
      ]
    }

Option 2: Using head command

    If you want to read and display only x number of files from the top of the JSON file.

    # head -n 5 data.json
     
    {
      "city": "New York",
      "forecast": [
        { "date": "2023-08-18", "temp": 78 },
        { "date": "2023-08-19", "temp": 82 },

Option 3: Using tail command

    If you want to read and display only x number of files from the bottom of the JSON file.

    # tail -n 5 data.json 
    
        { "date": "2023-08-20", "temp": 75 },
        { "date": "2023-08-21", "temp": 70 },
        { "date": "2023-08-22", "temp": 73 }
      ]
    }
    
    Read and Display JSON file content on Bash Shell Example


If you want to read and parse or manipulate a JSON file, then you should make use of the jq binary.

Make sure to install jq package

apt install jq

Example: Parsing and Manipulating JSON file

    Display the name of the city from the JSON file:
    # jq '.city' data.json
    
    "New York"
    
    Display the temp for each day:
    # jq '.forecast[].temp' data.json
    
    78
    82
    75
    70
    73
    Calculate average temp from JSON:
    # jq '[.forecast[].temp] | add / length' data.json
    
    75.6
    
    Reading and Manipulating JSON File in Bash Shell Example

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap