Read, Write, Decode, Encode JSON pada PHP


JSON (JavaScript Object Notation) adalah format file standar untuk pertukaran data antar aplikasi. Pada tutorial ini, kita akan belajar bagaimana melakukan manipulasi yang paling umum, seperti encoding, decoding, convert JSON to Array and Array to JSON. Kita juga akan membuat cara membaca dan menulis file JSON di PHP.

Contoh String JSON

Dalam tutorial ini, kita akan menggunakan string JSON berikut yang berisi daftar film dan propertinya.

[
    {
        "id": "287947",
        "title": "Shazam!",
        "poster": "https://image.tmdb.org/t/p/w500/xnopI5Xtky18MPhK40cZAGAOVeV.jpg",
        "overview": "A boy is given the ability to become an adult superhero in times of need with a single magic word.",
        "release_date": "1553299200",
        "genres": [
            "Action",
            "Comedy",
            "Fantasy"
        ]
    },
    {
        "id": "299537",
        "title": "Captain Marvel",
        "poster": "https://image.tmdb.org/t/p/w500/AtsgWhDnHTq68L0lLsUrCnM7TjG.jpg",
        "overview": "The story follows Carol Danvers as she becomes one of the universe\u2019s most powerful heroes when Earth is caught in the middle of a galactic war between two alien races. Set in the 1990s, Captain Marvel is an all-new adventure from a previously unseen period in the history of the Marvel Cinematic Universe.",
        "release_date": "1551830400",
        "genres": [
            "Action",
            "Adventure",
            "Science Fiction"
        ]
    }
]

Mengonversi string JSON menjadi array asosiatif menggunakan json_decode

Kita bisa menggunakan json_decode untuk mengonversi (memecahkan kode) string ke array asosiatif PHP. Parameter kedua json_decode menentukan apakah kita ingin mendapatkan setiap objek JSON sebagai array asosiatif atau sebagai objek. Di sini, kita pilih untuk opsi array asosiatif.

<?php
$jsonString = '[{"id":"287947","title":"Shazam!","poster":"https:\/\/image.tmdb.org\/t\/p\/w500\/xnopI5Xtky18MPhK40cZAGAOVeV.jpg","overview":"A boy is given the ability to become an adult superhero in times of need with a single magic word.","release_date":"1553299200","genres":["Action","Comedy","Fantasy"]},{"id":"299537","title":"Captain Marvel","poster":"https:\/\/image.tmdb.org\/t\/p\/w500\/AtsgWhDnHTq68L0lLsUrCnM7TjG.jpg","overview":"The story follows Carol Danvers as she becomes one of the universe\u2019s most powerful heroes when Earth is caught in the middle of a galactic war between two alien races. Set in the 1990s, Captain Marvel is an all-new adventure from a previously unseen period in the history of the Marvel Cinematic Universe.","release_date":"1551830400","genres":["Action","Adventure","Science Fiction"]}]';
$jsonArray = json_decode($jsonString, true); // true for associative arrays, false for objects
var_dump($jsonArray);

Hasilnya adalah array yang berisi satu array asosiatif untuk setiap film. Kunci dari setiap array asosiatif adalah bidang objek JSON.

<?php
array(2) {
  [0]=>
  array(6) {
    ["id"]=>
    string(6) "287947"
    ["title"]=>
    string(7) "Shazam!"
    ["poster"]=>
    string(63) "https://image.tmdb.org/t/p/w500/xnopI5Xtky18MPhK40cZAGAOVeV.jpg"
    ["overview"]=>
    string(98) "A boy is given the ability to become an adult superhero in times of need with a single magic word."
    ["release_date"]=>
    string(10) "1553299200"
    ["genres"]=>
    array(3) {
      [0]=>
      string(6) "Action"
      [1]=>
      string(6) "Comedy"
      [2]=>
      string(7) "Fantasy"
    }
  }
  [1]=> // ... the second movie
}

Mengonversi Array Asosiatif menjadi string JSON Menggunakan json_encode

Kita akan menggunakan json_encode untuk mengonversi array asosiatif ke string JSON. Parameter kedua json_encode menentukan format string. Kita bisa memilih compact format secara default. Kita juga bisa menggunakan pretty format. Ini termasuk jarak baris dan spasi yang membuat hasilnya lebih mudah dibaca.

<?php
$jsonArray = [
    [
        "id" => "287947",
        "title" => "Shazam!",
        "poster" => "https://image.tmdb.org/t/p/w500/xnopI5Xtky18MPhK40cZAGAOVeV.jpg",
        "overview" => "A boy is given the ability to become an adult superhero in times of need with a single magic word.",
        "release_date" => "1553299200",
        "genres"=> ["Action", "Comedy", "Fantasy"]
    ],
    [
        "id" => "299537",
        "title" => "Captain Marvel",
        "poster" => "https://image.tmdb.org/t/p/w500/AtsgWhDnHTq68L0lLsUrCnM7TjG.jpg",
        "overview" => "The story follows Carol Danvers as she becomes one of the universe’s most powerful heroes when Earth is caught in the middle of a galactic war between two alien races. Set in the 1990s, Captain Marvel is an all-new adventure from a previously unseen period in the history of the Marvel Cinematic Universe.",
        "release_date" => "1551830400",
        "genres"=> ["Action", "Adventure", "Science Fiction"]
    ]
];
// compact format
$compactJsonString = json_encode($jsonArray);
echo $compactJsonString.PHP_EOL;
// pretty human-readable format
$prettyJsonString = json_encode($jsonArray, JSON_PRETTY_PRINT);
echo $prettyJsonString.PHP_EOL;

Compact JSON string format:

<?php
[{"id":"287947","title":"Shazam!","poster":"https:\/\/image.tmdb.org\/t\/p\/w500\/xnopI5Xtky18MPhK40cZAGAOVeV.jpg","overview":"A boy is given the ability to become an adult superhero in times of need with a single magic word.","release_date":"1553299200","genres":["Action","Comedy","Fantasy"]},{"id":"299537","title":"Captain Marvel","poster":"https:\/\/image.tmdb.org\/t\/p\/w500\/AtsgWhDnHTq68L0lLsUrCnM7TjG.jpg","overview":"The story follows Carol Danvers as she becomes one of the universe\u2019s most powerful heroes when Earth is caught in the middle of a galactic war between two alien races. Set in the 1990s, Captain Marvel is an all-new adventure from a previously unseen period in the history of the Marvel Cinematic Universe.","release_date":"1551830400","genres":["Action","Adventure","Science Fiction"]}]


Pretty JSON string format:

<?php
[
    {
        "id": "287947",
        "title": "Shazam!",
        "poster": "https:\/\/image.tmdb.org\/t\/p\/w500\/xnopI5Xtky18MPhK40cZAGAOVeV.jpg",
        "overview": "A boy is given the ability to become an adult superhero in times of need with a single magic word.",
        "release_date": "1553299200",
        "genres": [
            "Action",
            "Comedy",
            "Fantasy"
        ]
    },
    {
        "id": "299537",
        "title": "Captain Marvel",
        "poster": "https:\/\/image.tmdb.org\/t\/p\/w500\/AtsgWhDnHTq68L0lLsUrCnM7TjG.jpg",
        "overview": "The story follows Carol Danvers as she becomes one of the universe\u2019s most powerful heroes when Earth is caught in the middle of a galactic war between two alien races. Set in the 1990s, Captain Marvel is an all-new adventure from a previously unseen period in the history of the Marvel Cinematic Universe.",
        "release_date": "1551830400",
        "genres": [
            "Action",
            "Adventure",
            "Science Fiction"
        ]
    }
]


Inspirasi: https://www.nidup.io/blog/manipulate-json-files-in-php

Posting Komentar

0 Komentar