How to Create and Edit JSON Files in Linux Terminal

Ben
Ben
@benjislab

JSON (JavaScript Object Notation) is a lightweight data interchange format that's easy for humans to read and write and easy for machines to parse and generate. This tutorial will cover how to create and edit JSON files using the Linux terminal, leveraging tools such as jq for effective manipulation.

Creating JSON Files You can create a JSON file by using any text editor in the Linux terminal. Here’s how to create an empty JSON file:

touch myfile.json

To open and edit it using Nano, use:

nano myfile.json

Simply write valid JSON content, such as:

{
  "name": "John Doe",
  "age": 30,
  "email": "[email protected]"
}

Editing JSON Files To edit JSON files effectively, utilize tools like jq, which can format and manipulate JSON data. To install jq:

sudo apt install jq

Example of Prettifying JSON To prettify JSON output from a file:

jq '.' myfile.json

If you want to prettify JSON from an API response, you can do:

curl http://api.example.com/data | jq '.'

Advanced jq Usages

  • Accessing Properties
jq '.name' myfile.json
  • Working with Arrays
echo '[{"name":"apple"},{"name":"banana"}]' | jq '.[] | .name'
  • Filtering based on Conditions
jq '.[] | select(.age > 25)' myfile.json
  • Transforming JSON Turning one JSON structure into another can be done using jq mappings.

Example of Transforming Data Suppose we have complex JSON data, we can transform it to a simpler structure:

jq '.items | map({title: .name, id: .id})' complex.json

Alternative Tools While jq is powerful, you might also consider:

  • fx: Interactive JSON viewer
  • json_pp: Simple JSON prettifier
  • python -m json.tool: Uses Python for basic formatting

Conclusion Working with JSON files in the Linux terminal can be simplified with tools like jq. This text provides foundational methods for creating, editing, and manipulating JSON files easily and effectively.