0

This is intended to be a general reference question and answer covering many of the never-ending "How do I access data in my JSON?" questions. It is here to handle the broad basics of decoding JSON in PHP and accessing the results. I have the JSON

JSONFile

[
    {
            "name": "Ubuntu",
            "flavor": [
                    {
                            "vcpu": "4",
                            "RAM": "8",
                            "HDD": "100"
                    }
            ],
          "department": [
                    {
                            "DPT": "IT",
                            "BU": "QnO"

                    }
            ],
           "location": "Texas"

    },
    {
            "name": "Centos",
            "flavor": [
                    {
                            "vcpu": "8",
                            "RAM": "16",
                            "HDD": "500"
                    }
            ],
             "department": [
                    {
                            "DPT": "LAB",
                            "BU": "QnO"

                    }
                     ],
          "location": "California"


    }
]

This is intended to be a general reference question and answer covering many of the never-ending "How do I access data in my JSON?" questions. It is here to handle the broad basics of decoding JSON in PHP and accessing the results.

How do I decode this in PHP and access the resulting data?

php file

   <?php
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection    
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}


$url = 'doublenested.json'; // path to your JSON file
$data = file_get_contents($url); // put the contents of the file into a variable
$characters = json_decode($data, true); // decode the JSON feed


foreach ($characters as $row) {

$sql = "INSERT INTO tbl_doublenested (name, vcpu, RAM, HDD, DPT, BU) VALUES ('".$row["name"]."', '".$row["flavor"][0]["vcpu"]."', '".$row["flavor"][0]["RAM"]."', '".$row["flavor"][0]["HDD"]."' '".$row["department"][0]["DPT"]."', '".$row["department"][0]["BU"]."'); ";

$conn->query($sql);
}
?>

Please help me in decoding the JSON code to MySQL, having problem in nested json code. Worked for normal JSON code. SQL INSER VALUES is having issues

Stark
  • 61
  • 1
  • 1
  • 6

0 Answers0