phparraysjsonnaming-conventionsundefined-index

Getting undefined index when retrieving json value of key name having a dot within in PHP


My JSON file has this structure:

[
  {
    "n.name": "name1",
    "n.section": ["section1"]
  },
  {
    "n.name": "name2",
    "n.section": ["section2a", "section2b"]
  },

I parse it and having no error:

$input = file_get_contents(__DIR__ . "/node.json");
$jsonclean = removeBOM($input);
$data = json_decode($jsonclean, true);
echo 'Error code: '. $error; //Error code: 0

I want to echo only the values of the n.name keys (e.g. name1 name2 name3...). However using echo $data['n.name']; yields:

Notice: Undefined index: n.name

According to "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP, this is just a way for PHP to be more secure, and my method should work in theory. I then try:

$value = isset($_POST['n.name']) ? $_POST['n.name'] : '';
$value = !empty($_POST['n.name']) ? $_POST['n.name'] : '';
echo $value;

But it prints nothing. I'm not sure if that's the correct way to debug this?


Solution

  • Your json is a array of items, so when you decode it with json_decode, you should iterate over each item and retrieve the key that you want. Example:

    $json = '[
      {
        "n.name": "name1",
        "n.section": ["section1"]
      },
      {
        "n.name": "name2",
        "n.section": ["section2a", "section2b"]
      }]';
    
      $data = json_decode($json, true);
    
      foreach($data as $item) {
          echo $item['n.name'] . "<br>";
      }
    

    Output:

    name1
    name2