0

I am trying to supply some data to a Javascript Function but right now i am unable to convert it to desired format.

The Correct Format that is Working is below.

    const eventsArr = [
    {
      day: 1,
      month: 1,
      year: 2023,
      events: [
        {
          title: "asdEvent 1 lorem ipsun dolar sit genfa tersd dsad ",
          time: "10:00 AM",
        } 
      ],
    },
    {
      day: 13,
      month: 11,
      year: 2022,
      events: [ 
        {
          title: "Event 2",
          time: "11:00 AM",
        },
      ],
    },
  ];

The format is am being able to produce is the following.

 const eventsArr = [
{
    "day": "18",
    "month": "2",
    "year": "2023",
    "events": [
        {
            "title": "Feb 18th Event and Updated From Databae",
            "time": "05:10"
        }
    ]
}

The Only difference between two javascript objects/arrays is that my version has "" around the keys and the working format does not have "" around the keys.

My Server Side PHP Code where i am using json_encode

$events  = []; 
foreach($db_data['CalendarEvent'] as $event)
{
    $single_event = array(
                        'day'=>$event->ce_day,
                        'month'=>$event->ce_month,
                        'year'=>$event->ce_year,
                        'events'=>array(
                                        array(
                                            'title'=> $event->ce_title,
                                            'time'=> $event->ce_time_from,
                                        )
                                      )
                        );

    $events[] = $single_event;
}
$db_data['all_events'] = json_encode($events , JSON_PRETTY_PRINT);

Can somebody help me in this? How can i produce the required format (without "" around the keys in javascript). What i am doing wrong? Thanks in Advance

Nomi
  • 27
  • 1
  • 6
  • 1
    JSON format naturally has `""` around the keys; you cannot change that and it is not the problem of `json_encode`. If you want to create a JavaScript object from the given JSON string, use (in JavaScript) `JSON.parse(jsonString)`, where `jsonString` is the value given by your PHP code `json_encode($events , JSON_PRETTY_PRINT)` – Neil Lu Feb 18 '23 at 19:50

0 Answers0