简体   繁体   中英

To Edit Json_encoded string

As i'm new to php i have little idea about how to format json data using preg_replace. I'm working on HTML5 charts and for that i'm fetching data from the database and encoding it using json_encode method. Now my desired result would be : [{label:"Apple",y:95},{label:"Robin",y:85},{label:"Ron",y:65},{label:"Roy",y:55},{lable:"Na",y:45}]

While what i have is : {"data":[[{"lable":"Apple","y":95},{"lable":"Robin","y":85},{"lable":"Ron","y":65},{"lable":"Roy","y":55},{"lable":"Na","y":45}]]}

What i have read is ill preg_replace method will be helpful but i dont know how. Please help. Any help will be appreciated. Thanks in advance.

Well it seems that your json is not valid. say for example i had this:

[{"label":"Apple","y":"95"},{"label":"Apple","y":"95"},{"label":"Apple","y":"95"}]

Then i wanted to decode this with php:

$json_convert_to_array = json_decode($json, true);

it would look like this:

 Array
(
    [0] => Array
        (
            [label] => Apple
            [y] => 95
        )

    [1] => Array
        (
            [label] => Apple
            [y] => 95
        )

    [2] => Array
        (
            [label] => Apple
            [y] => 95
        )

)

Then to edit a value and pack it back into json you can do this:

$json_convert_to_array[2]['label'] = "new Val";

print json_encode($json_convert_to_array);

should look like this now:

[{"label":"Apple","y":95},{"label":"Apple","y":95},{"label":"new Val","y":95}]

hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM