2

I know how to JSON encode and decode an object. That's no biggie. However, I've reached a situation where I need to save $this as a JSON string, and then later, populate $this's attributes from that JSON string.

In other words, I don't want to get a new instance of an object with the data from the JSON string, I want to apply it to an existing object.

How can I do that?

3
  • If an attribute is currently defined on $this but not defined on your encoded object, what do you want to happen with that attribute when you apply the encoded data to $this? Commented Apr 24, 2013 at 14:50
  • Nothing. Leave the attribute of $this to its old value. My object always has its attributes fully populated. Commented Apr 24, 2013 at 14:51
  • You can just use encode inside your class so you have the json inside your object as an object. Like $instance->jsonecodestuf->etc Commented Apr 24, 2013 at 14:53

1 Answer 1

1

You can get the defined attributes of an object using get_object_vars() http://php.net/manual/en/function.get-object-vars.php

class MyClass
{
    function populateFromJSON($data)
    {
        $o = json_decode($data);
        $attributes = get_object_vars($o);
        if (is_array($attributes)) {
            foreach ($attributes as $name => $val) {
                $this->$name = $val;
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Why not just use json_decode($data, true) which returns arrays instead of objects.
That leads to another issue with this answer. How does it handle attributes which are themselves objects? Not very well.
Very true; especially if they're instances of other objects, rather than just stdClass. There's no quick and dirty solution that solves all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.