derd1199
derd1199

Reputation: 31

PHP parsing JSON Data - No content

I can´t figure out what is wrong with my code, I have a JSON which is structured this way

{
   "data":[
      {
         "B00PM7UJMA":[
            {
               "Verkaufer":"Je Sens le Bonheur",
               "Stock":71.0,
               "Stock: Sold":7.0,
               "Stock: Sold 30 Days":7.0,
               "FBA":"no"
            },
            {
               "Verkaufer":"Parfumea",
               "Stock":2.0,
               "Stock: Sold":"NaN",
               "Stock: Sold 30 Days":"NaN",
               "FBA":"no"
            }
         ],
         "Insgesamt":[
            73.0
         ]
      }
   ]
}

I am trying to access the "Data" but it won´t work at all. I can´t figure out what the problem is, maybe there is something going on with my JSON?

This is my PHP

    $str = file_get_contents($row["URL"]);
    $json = json_encode($str); // decode the JSON into an associative array
    $jsondecode = json_decode($json, true);

    print_r($jsondecode['data']); // doesn´t work at all
    print_r($jsondecode->data); // doesn´t work either

Does someone know what the problem could be? I worked a lot with JSON via PHP. I bet the solution is really easy, but I just need someone others opinion on this one.

Thank you

Upvotes: 0

Views: 60

Answers (2)

Luuk
Luuk

Reputation: 14948

$str = '{"data":[{"B00PM7UJMA":[{"Verkaufer":"Je Sens le Bonheur","Stock":71.0,"Stock: Sold":7.0,"Stock: Sold 30 Days":7.0,"FBA":"no"},{"Verkaufer":"Parfumea","Stock":2.0,"Stock: Sold":"NaN","Stock: Sold 30 Days":"NaN","FBA":"no"}],"Insgesamt":[73.0]}]}';

$json = json_decode($str, false);

print_r($json->data);
print_r($json->data[0]);
print_r($json->data[0]->B00PM7UJMA);
print_r($json->data[0]->B00PM7UJMA[0]);
print_r($json->data[0]->B00PM7UJMA[0]->Verkaufer);

The final line prints: "Je Sens le Bonheur"

Upvotes: 0

Gunobaba
Gunobaba

Reputation: 176

I arranged your code a bit. You are encoding first and after that decoding again. I think it is redundant.

If you give $str directly to decode, it will work.

$jsondecode = json_decode($str);
print_r($jsondecode->data);

Also if you want to take the output as an array, you should add true to json_decode and print with square brackets like that

$jsondecode = json_decode($str, true);
print_r($jsondecode['data']);

Upvotes: 4

Related Questions