Cannot access JSON object: it is not defined

After a user adds markers to the Google Map, I store the data as a JSON string in my MySQL database. The latitude and longitude of each marker are represented by "k" and "D," respectively:

    [{"k":52.908902047770255,"D":-3.427734375},{"k":56.31653672211301,"D":7.03125}]

Additionally, I save the polylines connecting the markers in this format:

 [[52.908902047770255,-3.427734375],[56.31653672211301,7.03125]]

To retrieve all the markers and polylines from the database for display, I use the following query:

 function getMarkersByTripId($tripId)
 {
   if ($bdd = mysqli_connect(_BDD_HOST_, _BDD_USERNAME_, _BDD_PASSWORD_, _BDD_NAME_)) {

     $sql = 'SELECT DISTINCT `markers`, `polylines` FROM `trip` WHERE `trip_id` = "'.$tripId.'"';
    $req = mysqli_query($bdd, $sql);

    if ($req) {
        while ($row = mysqli_fetch_row($req)) {
            $jsonData= array('markers'=>$row[0], 'polylines'=>$row[1]);
        }
        echo json_encode($jsonData);
    }

     else {
         echo json_encode(array('status' => 'failure'));
     }
   }

     if ($bdd) {
        mysqli_close($bdd);
   }
}

A var_dump of $jsonData reveals the structure as follows:

 array(2) {
            ["markers"]=>
            string(79) "[{"k":52.908902047770255,"D":-3.427734375},{"k":56.31653672211301,"D":7.03125}]"
            ["polylines"]=>
             string(63) "[[52.908902047770255,-3.427734375],[56.31653672211301,7.03125]]"
 }

In my JavaScript code, when I log the jsonText variable, it is formatted like this:

 "{"markers":"[{\"k\":52.908902047770255,\"D\":-3.427734375},{\"k\":56.31653672211301,\"D\":7.03125}]","polylines":"[[52.908902047770255,-3.427734375],[56.31653672211301,7.03125]]"}"

I then attempt to convert this JSON string into an object using JSON.parse() method:

 var jsonData =  JSON.parse(jsonText);  
 console.log(jsonData);

The parsing seems successful with the output resembling:

 Object { markers: "[{"k":52.908902047770255,"D":-3.427734375},{"k":56.31653672211301,"D":7.03125}]", polylines: "[[52.908902047770255,-3.427734375],[56.31653672211301,7.03125]]" }

However, the issue arises when trying to access the latitude/longitude values ("k"/"D" elements) after parsing the JSON data:

   console.log(jsonData['markers'].k);

This always returns "undefined," preventing me from adding the marker to the map. I suspect that the JSON parsing may be affected by double quotes added during retrieval from the MySQL database. Any guidance on resolving this would be greatly appreciated.

Answer №1

jsonData.markers is encoded twice using JSON, so the first step is to parse the key object within jsonData.markers.

var jsonText = {
  "markers": "[{\"k\":52.908902047770255,\"D\":-3.427734375},{\"k\":56.31653672211301,\"D\":7.03125}]",
  "polylines": "[[52.908902047770255,-3.427734375],[56.31653672211301,7.03125]]"
};


var markers = JSON.parse(jsonText.markers);
var polylines = JSON.parse(jsonText.polylines);
console.log('markers  ', markers, ' polylines', polylines);

In PHP code: wrap markers, polylines with json_decode() function in a while loop, as both values are already JSON strings. This prevents double encoding when using json_encode again.

while ($row = mysqli_fetch_row($req)) {
  $jsonData= array(
       'markers'=>json_decode($row[0]), 
       'polylines'=>json_decode($row[1])
  );
}

UPDATE PHP CODE

<?php
$arr1 = array(
 "markers" => '[{"k":52.908902047770255,"D":-3.427734375},{"k":56.31653672211301,"D":7.03125}]',
 "polylines" =>'[[52.908902047770255,-3.427734375],[56.31653672211301,7.03125]]'
);

echo "//your problem \n";
echo json_encode($arr1);

$arr2 = array(
 "markers" => json_decode('[{"k":52.908902047770255,"D":-3.427734375},{"k":56.31653672211301,"D":7.03125}]'),
 "polylines" =>json_decode('[[52.908902047770255,-3.427734375],[56.31653672211301,7.03125]]')
);


echo "\n\n//my solution\n";
echo json_encode($arr2);

//after solution markers, polylines keys wrapped with one more array so you will need to use `[0]` index in javascript
// jsonText.markers[0].k;   jsonText.markers[0].d etc

// you can also do

$arr3 = array(
 "markers" => array_shift(json_decode('[{"k":52.908902047770255,"D":-3.427734375},{"k":56.31653672211301,"D":7.03125}]')),
 "polylines" =>array_shift(json_decode('[[52.908902047770255,-3.427734375],[56.31653672211301,7.03125]]'))
);


echo "\n\n//another one more solution my solution\n";
echo json_encode($arr3);

//now you can access values in JavaScript
// jsonText.markers.k;   jsonText.markers.d etc

?>

see more detail click here

Answer №2

Identify the 'markers' member as an array and specify which element's coordinates you need from this array. Test accessing the first one by using this code:

console.log(jsonData['markers'][0].k);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Which Angular2 npm packages should I be installing?

When I'm trying to create an empty app without using angular-cli, it's really difficult for me to figure out which packages or libraries to include. Searching for angular2 on npmjs yields unwanted results, forcing me to click through multiple li ...

Ways to expand the `Array.prototype` from an external library in a Node.js environment

While enjoying my time on hackerrank with pure JavaScript, I decided to steer clear of extra arrays or math libraries, unlike the convenience of using python. My approach is robust, but now I'm considering utilizing sugar.js or underscore. I came acr ...

Transforming a serialized JSON file back into its original format

I've encountered a situation where I have a JSON file that has been serialized via an API, and now I need to deserialize it in order to utilize the data within my code. However, I'm facing an Exception Unhandled error that has left me struggling ...

Supabase authentication in a React app is causing a TypeError: Unable to access properties of undefined (specifically 'user')

In the development of my React application using Next.js, I've integrated Supabase for authentication. I've created a custom hook named useAuthentication to verify if the user is logged in and redirect them to the login page if they're not. ...

Looking for tips on how to handle JSON parsing in .NET

What is the most effective method for parsing this JSON data in c# .NET? {"data":{"5":{"isDeleted":"false","day":"THU"}},"action":"edit"} {"data":{"7":{&quo ...

A guide to fetching stream data from a NestJS endpoint

I'm currently working on developing a micro-service that sends data to another core service whenever a request is made to it. Initially, I dealt with a large JSON payload using the following code snippet: @Get('/zzz/stream') async streamTil ...

Navigating the AngularJS Directive Controller

I am encountering difficulties while trying to access my controller within a directive that I am attempting to unit test using jasmine and karma testrunner. The structure of the directive is as follows: directive angular.module('Common.accountSearch ...

Strange output observed when using the Mongoose findById method

Currently, I am in the process of developing a Rest API using node.js, express, and mongoDb. One of the endpoints I have set up is for user registration, where user details are simply added to the database. The User Schema is structured as follows: const ...

JavaScript and Ajax functions are only compatible with the use of the confirm() method

After some troubleshooting, I discovered that my JavaScript function only works when the final confirm() statement is included. Originally added for debugging purposes, removing it prevents delete_row.php from running. Additionally, when the confirm statem ...

Clicking on different elements to activate the like button with JavaScript

Being a JS novice, I am faced with an issue while working on my personal project. I am trying to add a toggle-like button for multiple pictures but the current implementation only works for one photo. How can I create a loop to make the same button work fo ...

Tips for sorting through the state hook array and managing the addition and removal of data within it

Having trouble finding a solution for filtering an array using the React useState hook? Let me assist you. I have declared a string array in useState- const [filterBrand, setFilterBrand] = useState<string[]>([]); Below is my function to filter this ...

When the directive manually replaces the element's content, ngRepeat fails to remove the old entries

I created a directive that utilizes different templates based on the state of the scope as shown below: app.directive('foo', function($compile) { return { restrict: 'E', scope: { bar: '=' }, link: func ...

How can I prompt TypeScript to flag null comparisons with a non-nullable field?

Is there a way to have TypeScript detect this issue? My strictNullChecks setting is enabled. const foo: string = 'asdf'; if (foo !== null) { console.log(foo); } If I modify that condition to: if (foo !== 42) { The error message displayed ...

Uncovering the Mystery of AJAX and JSON in jQuery and NodeJS

Currently, I'm facing a challenge with an ajax function that sends a json to a nodejs route. I need to extract the selected values from 4 button-groups named quality, costeffectiveness, deliveryscope, and rating. Each button-group consists of 5 radio- ...

Implementing an event handler within a functional component using hooks in React

I'm currently exploring functional components and hooks. I have a component that retrieves an array of quotes from an API and is supposed to randomly select one to pass as a prop to a child component named "Quote". import React, {useState, useEffect} ...

Layering SVG Images for Added Depth

I've been brainstorming a concept for a map that includes Layers functionality. Starting with an initial map image in SVG format, my goal is to incorporate Layers onto it. Each layer will contain a set of objects (polygon coordinates). After drawing ...

Display images fetched using ajax requests

Looking to retrieve the image source path using the code below: $.ajax({ url: 'api/catalogs.php?action=fetchimg&CatalogId=' + d.CategoryId, type: 'GET', dataType: "json", success: function(response) { var path = respo ...

Using jQuery to select a specific checkbox from a group of checkboxes with identical IDs

There is an issue with multiple checkboxes having the same ID in an asp.net repeater control. Users can select either email or phone against each record in the repeater rows. In the example below, there are two rows. If you select the email icon in the fi ...

Develop a design utilizing a foundational database entity

I'm new to AngularJS and I am seeking guidance on how to properly separate the model from the controller. In my previous experience, I have always integrated models within the controllers. For example: angular.module("app").controller("customerContr ...

The process of isolating each variable within a JSON data structure

After making an ajax call, my JSON data is currently displayed in this format: {"main_object":{"id":"new","formData":"language=nl_NL&getExerciseTitle=test&question_takeAudio_exerciseWord%5B0%5D=test&Syllablescounter%5B0%5D=test&Syllablesco ...