开发者

Needing help with JSON problems

i'm with this problem at PHP when i'm try to convert an array to an json I have an recursive function that build the array to encode it on jSon format.

That's the array:

$data = array(
    array('id' => 1, 'parent_id' => null, 'text' => 'lorem ipsum'),
    array('id' => 2, 'parent_id' => 1, 'text' => 'lorem ipsum1'),
    array('id' => 3, 'parent_id' => 1, 'text' => 'lorem ipsum2'),
    array('id' => 4, 'parent_id' => 2, 'text' => 'lorem ipsum3'),
    array('id' =>开发者_开发问答; 5, 'parent_id' => 3, 'text' => 'lorem ipsum4'),
    array('id' => 6, 'parent_id' => null, 'text' => 'lorem ipsum5'),
);

Thats my function:

function trataArray($data) {


$itemsByReference = array();

// Build array of item references:
foreach ($data as $key => &$item) {
    $itemsByReference[$item['id']] = &$item;
    // Children array:
    $itemsByReference[$item['id']]['children'] = array();
    // Empty data class (so that json_encode adds "data: {}" )
    $itemsByReference[$item['id']]['data'] = new StdClass();
}

// Set items as children of the relevant parent item.
foreach ($data as $key => &$item)
    if ($item['parent_id'] && isset($itemsByReference[$item['parent_id']]))
        $itemsByReference [$item['parent_id']]['children'][] = &$item;

// Remove items that were added to parents elsewhere:
foreach ($data as $key => &$item) {
    if ($item['parent_id'] && isset($itemsByReference[$item['parent_id']]))
        unset($data[$key]);
}

// Encode:
return $data;

}

Thats my json, but this json have errors:

{
    "0": // Problem here... T_T
     {
        "id": 1,
        "parent_id": null,
        "name": "lorem ipsum",
        "children": [
            {
                "id": 2,
                "parent_id": 1,
                "name": "lorem ipsum1",
                "children": [
                    {
                        "id": 4,
                        "parent_id": 2,
                        "name": "lorem ipsum3",
                        "children": [],
                        "data": {}
                    }
                ],
                "data": {}
            },
            {
                "id": 3,
                "parent_id": 1,
                "name": "lorem ipsum2",
                "children": [
                    {
                        "id": 5,
                        "parent_id": 3,
                        "name": "lorem ipsum4",
                        "children": [],
                        "data": {}
                    }
                ],
                "data": {}
            }
        ],
        "data": {}
    },
    "5":  // And here... T_T
    {
        "id": 6,
        "parent_id": null,
        "name": "lorem ipsum5",
        "children": [],
        "data": {}
    }
}

The strings "0": and "5": are causing an error on json markup. i thinked to try to remove it using preg_replace but i'm terrible working with regular expressions. Someone could help me with it... :D

Thanks guys!


I had an idea... :)

I was looking for ways to test thins shit... :D And i come with an idea, get the JSON from the plugin and ENCODE it as one array and print it to see what i would need to give to JSON Encode to give me the correct thing.

Them he reproduce it:

    Array
(
    [0] => stdClass Object
        (
            [id] => 1
            [text] => City
            [children] => Array
                (
                    [0] => stdClass Object
                        (
                            [id] => 11
                            [text] => Wyoming
                            [children] => Array
                                (
                                    [0] => stdClass Object
                                        (
                                            [id] => 111
                                            [text] => Albin
                                        )

                                    [1] => stdClass Object
                                        (
                                            [id] => 112
                                            [text] => Canon
                                        )

                                    [2] => stdClass Object
                                        (
                                            [id] => 113
                                            [text] => Egbert
                                        )

                                )

                        )

                    [1] => stdClass Object
                        (
                            [id] => 12
                            [text] => Washington
                            [state] => closed
                            [children] => Array
                                (
                                    [0] => stdClass Object
                                        (
                                            [id] => 121
                                            [text] => Bellingham
                                        )

                                    [1] => stdClass Object
                                        (
                                            [id] => 122
                                            [text] => Chehalis
                                        )

                                    [2] => stdClass Object
                                        (
                                            [id] => 123
                                            [text] => Ellensburg
                                        )

                                    [3] => stdClass Object
                                        (
                                            [id] => 124
                                            [text] => Monroe
                                        )

                                )

                        )

                )

        )

)

The JSON its base on OBJECTS, i think the bug its there, im tryng to work with arrays and convert it, when the data its an object.

Someone knows how to create something like it? Just an way to i can think... Thanks guys...

:DDD


According to jslint.com, this is valid JSON. It passes the validator just fine.


How are you seeing the error?

Simply pasting your JSON directly into <script> blocks and loading that in a browser raises errors both in IE and Chrome, however, assigning the same JSON to a variable first prevents any error messages. The Closure Compiler confirms these findings; when your bare JSON is run through compilation, it fails. When a simple variable assignment is introduced, everything compiles fine.

It seems there are some lexical rules of JS that I'm not aware of that is affecting this; sadly, I'm not sure exactly what the root cause is.

Also, I'm not sure how exactly you're producing the resultant JSON. I mean, I know you're using json_encode(), but no matter what I do with the array key, I cannot reproduce your output using an array in PHP.

I am looking to mimic this:

{"0": "foo"}

However, using numeric array keys in PHP will mean that the resultant JSON will be an array; for example:

json_encode( array(0 => 'foo') );
> (string) ["foo"]
json_encode( array("0" => 'foo') );
> (string) ["foo"]

The ONLY way that I can recreate your JSON is by doing the following:

$x = new stdClass;
$x->{"0"} = 'foo';
json_encode($x);
> (string) {"0": "foo"}

So, I'm thinking either your example is incomplete/misleading/wrong, or you've uncovered some extremely obscure bug in PHP.

Introducing spaces to the key, and other permutations like the following, also does not produce your JSON:

json_encode( array("0 " => 'foo') );
> (string) {"0 ": "foo"}

json_encode( array(" 0" => 'foo') );
> (string) {" 0": "foo"}

json_encode( array("00" => 'foo') );
> (string) {"00": "foo"}

json_encode( array(false => 'foo') );
> (string) ["foo"]

json_encode( array(null => 'foo') );
> (string) {"": "foo"}

json_encode( array("" => 'foo') );
> (string) {"": "foo"}

So, not sure what's going on.


try something like this:

var $counter = 0;
foreach ($data as $key => &$item) {
    $itemsByReference[$counter] = &$item;
    // Children array:
    $itemsByReference[$counter]['children'] = array();
    // Empty data class (so that json_encode adds "data: {}" )
    $itemsByReference[$counter]['data'] = new StdClass();

    $counter++;
}

This way you don't create an associative array and after encoding, it should not give you the "0" and "5" as keys. It will just be an array of objects.


That is because you should'nt define the 0 to 5 as string. You should define it as int, so you don't even have to name it. Like this:

[
      {
           // This will be 0
      },
      {
           // This will be 1, and so on
      }
]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜