简体   繁体   中英

Converting Json String to Json Object PHP

I have a json output as this

"data": [
    {
        "id": 1,
        "schedule": "{\"batch\": 1, \"times\": \"18:25:00.000000\"},{\"batch\": 1, \"times\": \"18:25:00.000000\"}"
    }

I want to display it like this

"data": [
    {
        "id": 1,
        "schedule": [{"batch": 1, "times": "18:25:00.000000"},
                     {"batch": 1, "times": "18:25:00.000000"}]
    }

I have tried everything I can think of, would appreciate some help

Neither your input JSON, nor your expected output JSON are well-formed. json_decode() returns NULL on both.

Without being exactly sure what your input looks like (or what your intended output would be), here is a demo of something that I suspect is what you're after. See comments for explanation.

<?php

// Your input JSON, corrected to well-formed syntax.
$string = '{"data": [
    {
        "id": 1,
        "schedule": "{\"batch\": 1, \"times\": \"18:25:00.000000\"},{\"batch\": 1, \"times\": \"18:25:00.000000\"}"
    }]}';

// Convert into native array.
$array = json_decode($string, TRUE);
// Make 'schedule' an array of the two batches.
$array['data'][0]['schedule'] = json_decode("[{$array['data'][0]['schedule']}]", TRUE);

echo json_encode($array) . "\n";
// {"data":[{"id":1,"schedule":[{"batch":1,"times":"18:25:00.000000"},{"batch":1,"times":"18:25:00.000000"}]}]}

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