Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read and parse the json file and add it into the shell script variable?

Tags:

json

linux

shell

I am having the file named loaded.json which contains the below json data.

    {
        "name" : "xat",
        "code" : "QpiAc"
    }
    {
        "name" : "gbd",
        "code" : "gDSo3"
    }
    {
        "name" : "mbB",
        "code" : "mg33y"
    }
    {
        "name" : "sbd",
        "code" : "2Vl1w"
    }

Form the shell script i need to read and parse the json and add the result to the variable and print it like this.

#!/bin/sh
databasename = cat loaded.json | json select '.name'
echo $databasename

When i run the above script i am getting error like

databasename command not found
json command not found

I am new to shell script please help me to solve this problem

like image 801
Soorya Prakash Avatar asked Jan 28 '15 06:01

Soorya Prakash


People also ask

Can we parse JSON in shell script?

By default shells like Bash do not have a standard JSON parser included. You would either have to drop into a programming language interpreter or install a small dedicated utility. If you're trying to stay within the confines of the shell, then adding a program is arguably the most straightforward option.

How do I parse a JSON file?

If you need to parse a JSON string that returns a dictionary, then you can use the json. loads() method. If you need to parse a JSON file that returns a dictionary, then you can use the json. load() method.

How read data from JSON file and convert it to a JavaScript object?

Use the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); Make sure the text is in JSON format, or else you will get a syntax error.

How do I read a JSON file in Linux?

Vim is a file opener software that can be used to open the JSON file on Linux platform. GitHub Atom is a cross-platform tool to open JSON files. Other than these tools, you can use web browsers like Google Chrome and Mozilla Firefox to open JSON files, which we discuss in detail later.


1 Answers

Replace this,

databasename=`cat loaded.json | json select '.name'`

or try jq command,

databasename=`jq '.name' loaded.json`

For more information read this article.

like image 74
Skynet Avatar answered Sep 21 '22 11:09

Skynet