Thread: Get json value

    #1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2004
    Posts
    82
    Rep Power
    10

    Get json value


    I have a json string similar to this:

    {"data":{"message":"New Account","value":"1010"}}

    I need to capture the number in the "value" field. I'm using json_decode but i'm having a brain fart and can't get the value field. any help would be appreciated.

    thanks
  2. #2
  3. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Location
    Hannover, Germany
    Posts
    11
    Rep Power
    0
    Hey utexas10,

    json_decode() returns a object. In your case, the value field, or property, would be accessed like this:
    php Code:
     
    $json = '{"data":{"message":"New Account","value":"1010"}}';  
    $d = json_decode($json);  
    echo $d->data->value;


    alternatively you can have json_decode return an associative array by passing a second parameter as true:
    php Code:
     
    $json = '{"data":{"message":"New Account","value":"1010"}}';  
    $d = json_decode($json, true);  
    echo $d["data"]["value"];


    I hope that helped.

    A tip for the future:
    Try using var_dump() to inspect you variable to find out, of what type they are and how they are nested.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2004
    Posts
    82
    Rep Power
    10
    thanks a lot, that was it. I was trying a variation of the $d->data->value but didn't have the "true" value in the json_decode function.
  6. #4
  7. Sarcky
    Devshed Supreme Being (6500+ posts)

    Join Date
    Oct 2006
    Location
    Pennsylvania, USA
    Posts
    10,908
    Rep Power
    6351
    If you were using an array in object context you should have gotten an error.
    HEY! YOU! Read the New User Guide and Forum Rules

    "They that can give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety." -Benjamin Franklin

    "The greatest tragedy of this changing society is that people who never knew what it was like before will simply assume that this is the way things are supposed to be." -2600 Magazine, Fall 2002

    Think we're being rude? Maybe you asked a bad question or you're a Help Vampire. Trying to argue intelligently? Please read this.

IMN logo majestic logo threadwatch logo seochat tools logo