views:

352

answers:

2

Hi,

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.

+4  A: 

You were close:

private function parseData($json){
  $decodeData = json_decode($json);
  $list = $decodeData['lists'];
  $this->output .= $list
}
cletus
yes you were very close indeed! cletus was even closer
I__
+1  A: 
{
    "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?

troelskn
i'm new to json, why does it validate here http://www.jsonlint.com/ ?
minimalpop
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).
troelskn