2

I'm trying to combine multiple JSON objects into a single one in PHP. I'm iterating through the JSON objets, decoding them, parsing out the parts I want to keep, and storing them in a property in my php class.

Supposing my json objects look like the following format:

{
    "lists" : {
        "list" : [
            {
                "termA" : 2 ,
                "termB" : "FOO" 
            } 
        ] 
    } 
}

I want to eventually combine everything into a JSON object like so.

{
    "lists" : {
        "list" : [
            {
                "termA" : 2 ,
                "termB" : "FOO" 
            },
            {
                "termA" : 2 ,
                "termB" : "FOO" 
            } 
        ] 
    } ,
    "lists" : {
        "list" : [
            {
                "termA" : 4 ,
                "termB" : "BAR" 
            },
            {
                "termA" : 4 ,
                "termB" : "BAR" 
            } 
        ] 
    } 
}

I'm trying to store Arrays in a property within my class in a function that gets called iteratrivley:

   private function parseData($json){
        $decodeData = json_decode($json);
            $list = $decodeData->lists;
        $this->output .= $list
    }

However I get the following error during the "$this->output .= $list" line.

Object of class stdClass could not be converted to string

Right now $this->output has no initial value. What might be the best way to store the "list" arrays temporarily, and then reformat them after going through all of the json objects?

Thanks.

2 Answers 2

7

You were close:

private function parseData($json){
  $decodeData = json_decode($json);
  $list = $decodeData['lists'];
  $this->output .= $list
}
Sign up to request clarification or add additional context in comments.

Comments

2
{
    "lists" : {
      ...
    } ,
    "lists" : {
      ...
    } 
}

That's not valid/meaningful JSON. You have a hash with the same key (lists) in it twice. How would you address that?

1 Comment

Because jsonlint is insufficient? The restriction is not syntactic, so that's probably why. See: rfc-4627, section 2.2 for the definition (Or think about it twice - It's quite intuitive).

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.