-1

I have a JSON string that I parsed as a PHP object, there are certain values I want to print from the string, how do I print the exact value I need.

I have provided the code below

{
  "data":
    {
      "id":123, 
      "name": "abc", 
      "gsm":"1133", 
      "metadata": 
      {
        "cart_id":13243
      }, 
      "customer": 
      {
        "id":123,
        "email": "a@ma.co"
      }
    }
}

json_decode($string);

for instance "name": abc, I want to print just abc

Saeid Amini
  • 1,313
  • 5
  • 16
  • 26
Abdullah
  • 11
  • 5
  • 1
    Your JSON is invalid. and once you correct your JSON then `$jsondecodeoutput->data->name` – Rahul Sep 06 '19 at 10:10

4 Answers4

0

You can convert JSON to an array and access the element by key

$jArr = json_decode($string, true);

Access the elements

$jArr['data']['name']
Rakesh Jakhar
  • 6,380
  • 2
  • 11
  • 20
0

Your JSON string is not valid, You missing bracket in it.Also string value must contain quotes in json. Your string should be like

$string= '{
  "data": {
    "id": 123,
    "name": "abc",
    "gsm": 1133,
    "metadata": {
      "cart_id": 13243
    },
    "customer": {
      "id": 123,
      "email": "a@ma.co"
    }
  }
}';

$response = json_decode($string);
print_r($response->data->name);
die;

Hope this helps you.

Rajdip Chauhan
  • 345
  • 2
  • 11
0

For example:

$string = '{"data":{"id":123}}';

$jsonObj = json_decode($string, true);

echo $jsonObj['data']['id'];
tom
  • 9,550
  • 6
  • 30
  • 49
0

You have to access the elements from json decode, like this:

$JSON = '{
    "data":{
        "id":123,
        "name": abc,
        "gsm":1133,
        "metadata":{
            "cart_id":13243
        },
        "customer":{
            "id":123,
            "email": "a@ma.co"
        }
    }
}'; //There were three errors, you have to to use ' insted of " for including the JSON string, you missed one '}' and you forgot the "" in the 'email' value under 'customer' section

$object = json_decode($JSON);
echo 'Printing the customer id using an object: '.$object->data->customer->id.PHP_EOL.PHP_EOL;

$array = json_decode($JSON, true);
echo 'Printing the customer id using an array: '.$array['data']['customer']['id'];

This code prints:

Printing the customer id using an object: 123

Printing the customer id using an array: 123