Cara parsing file JSON dengan jq
File json banyak ditemui dalam kegiatan sehari-hari baik programmer, system/network engineer, dll.
File Json mempunyai struktur, pada tutorial ini hanya akan membahas bagaimana memparsing/mengurai file Json, misalnya hanya mengambil bagian data-data yang dibutuhkan saja.
Disini menggunakan command jq, sebelum menggunakan perintah ini bisa menginstall terlebih dahulu, disini menggunakan linux, #sudo apt install jq
Gambar dibawah ini bagus memperlihatkan bagaimana format file json, isi file json pada dasarnya berisi data type pada umumnya.
Contoh ada file json dibawah ini:
score.json
{
"eventname": "Lomba Siswa",
"modulename": "Linux Project",
"competitors": [
{
"username": "competitor1",
"score": "98",
"institution": "SMK Negeri 4"
},
{
"username": "competitor2",
"score": "78",
"institution": "SMK Swasta 1"
},
{
"username": "competitor3",
"score": "70",
"institution": "SMK Negeri 11"
},
{
"username": "competitor4",
"score": "71",
"institution": "SMK Negeri 10"
},
{
"username": "competitor5",
"score": "87",
"institution": "SMK Negeri 4"
},
{
"username": "competitor6",
"score": "70",
"institution": "SMK Negeri 8"
},
{
"username": "competitor7",
"score": "79",
"institution": "SMK Swasta 5"
},
{
"username": "competitor8",
"score": "62",
"institution": "SMK Negeri 2"
},
{
"username": "competitor9",
"score": "50",
"institution": "SMK Swasta 1"
}
]
}
Berikut contoh untuk menggunakan command jq
Usage: jq [options] <jq filter> [file...]
1. Case 1
Menampilkan semua isi file json
cat score.json | jq .
2. Case 2
Menampilan data didalam array competitors, cukup tulis key name nya competitors maka akan keluar value nya.
cat score.json | jq .competitors
results:
[
{
"username": "competitor1",
"score": "98",
"institution": "SMK Negeri 1"
},
{
"username": "competitor2",
"score": "78",
"institution": "SMK Swasta 1"
},
{
"username": "competitor3",
"score": "70",
"institution": "SMK Negeri 11"
},
{
"username": "competitor4",
"score": "71",
"institution": "SMK Negeri 10"
},
{
"username": "competitor5",
"score": "87",
"institution": "SMK Negeri 4"
},
{
"username": "competitor6",
"score": "70",
"institution": "SMK Negeri 1"
},
{
"username": "competitor7",
"score": "79",
"institution": "SMK Swasta 5"
},
{
"username": "competitor8",
"score": "62",
"institution": "SMK Negeri 2"
},
{
"username": "competitor9",
"score": "50",
"institution": "SMK Swasta 1"
}
]
Komentar