The outcomes of JSON.stringify and JSON.parse can vary

I am facing an issue with using JSON.stringify to create a JSON string from an Object. After saving the string into a file, I attempt to read the file and use JSON.parse to retrieve the object again. However, it seems that the process is not working as expected. For instance, when trying to select elements using [i], it only retrieves the charset as if it were a string.

Can anyone provide assistance on how to resolve this?

The following is just a simplified example, as the actual JSON data is extensive:

{"featureCollection":
{"layers":"[
    {\"layerDefinition\": 
        {\"currentVersion\": 10.3,
                         \"id\": 0, 

                                     \"supportsCoordinatesQuantization\": true,
                                     \"advancedQueryCapabilities\": 
                                     {  
                                        \"supportsPagination\": true,

                                        \"supportsDistinct\": true
                                    }, 
                                    \"geometryType\": 
                                        \"esriGeometryPolygon\", \"minScale\": 0,
                                        \"maxScale\": 0,
                                        \"extent\": 
                                            {},
                                        \"drawingInfo\":
                                            {\"renderer\": 
                                                {\"type\": \"simple\", \"symbol\": 
                                                    {\"type\": \"esriSFS\", \"style\": \"esriSFSSolid\", \"color\": [76, 129, 205, 191], \"outline\": 
                                                        {\"type\": \"esriSLS\", \"style\": \"esriSLSSolid\", \"color\": [0, 0, 0, 255], \"width\": 0.75}
                                                    }
                                                },

Answer №1

The issue here is that the layers attribute within the featureCollection object is not in array format, but rather a JSON-encoded version of an array. To properly process the contents, you will need to decode it again. If we assume that json_obj represents the complete object, you should execute the following:

var layers = JSON.parse(json_obj.featureCollection.layers);

After this step, you can access

layers[i].layerDefinition.currentDefinition
.

The reasoning behind this approach is unclear. It may be beneficial to address the code responsible for generating the initial JSON and eliminate the section that utilizes JSON.stringify() when inserting data into the layers property.

Answer №2

It appears that the procedure responsible for writing the JSON data to a file is including escaped quotes, leading to parsing problems. To resolve this issue, you have two options: either prevent the process from escaping the quotes in the first place, or utilize the replace function to remove the escaped quotes from your JSON string before attempting to parse it.

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

What is the best way to connect the "areaName" with the <TextBox> attributes value="" and onChange=""?

After calling an API and mapping the array, I have successfully bound the data on <TableCell> {this.state.allArea.map((allArea, i) => ( <TableRow > <TableCell >{allArea.areaName}</TableCe ...

Pass the AngularJS object to a different MVC Controller when a button is clicked in the MVC view

When a button is clicked on the view, I need to pass an AngularJs object to another controller. CHTML <div ng-repeat="hotel in respData.hotels"> <button type="button" class="btn" data-ng-click="setTab(hotel.code)">Check Availability</bu ...

What is the best way to retrieve a particular element from a dictionary?

In my dictionary structure, I have a list containing 2 dictionaries. Here is an example: dict: { "weather":[ {"id": 701, "main": "Mist", "description": "mist"}, {"id": 300, "main": "Drizzle", "description": "light intensity drizzle"} ] } If I wan ...

The concept of matryoshka logic applied to data manipulation

"mainData"{ entities:[] }, "data2":{ entities:[ { name:"mainData": //entites }, { name:"mainData": //entites }, { name:"m ...

The hover effect is not altering the color

$(document).ready(function() { $(window).scroll(function() { var scroll = $(window).scrollTop(); if (scroll > 200) { $(".nav-bg").css({ "background": "#fff", ...

Identify the position of a mouse click event when dots overlap

Experience this live demo on CodePen by visiting it here. 1) When you click on the grid, a first red point will be added. 2) Click on the grid again to add a second red point. 3) By clicking back on the first red point, you may notice that the coordinat ...

Conceal the Submit button upon completing the form submission using the load method

When creating a form and sending a request to another page, I use the following code: $(document).ready(function() { $("#send").click(function() { var text = $("#text").val(); var email = $("#email").val(); $("#exp").load("sendmail.php",{text: ...

Ways to transform epoch timestamp to present timestamp?

Is there a way to accurately convert an epoch timestamp in milliseconds to the current timestamp in milliseconds? My Attempt: var currentTime = (resp.timestamp * 1000) + 1980000000; resp.timestamp represents the epoch timestamp I attempted to add 5 ho ...

When a fresh tile is loaded in Mapbox, an event is triggered

As I work with the Mapbox GL JS API to manipulate maps, I find myself wondering if there is an event that can inform me whenever a new tile HTTP request is made. My code snippet looks like this: map.on("dataloading", e => { if(e.dataType ...

Swap out the image backdrop by utilizing the forward and backward buttons

I am currently working on developing a Character Selection feature for Airconsole. I had the idea of implementing this using a Jquery method similar to a Gallery. In order to achieve this, I require a previous button, a next button, and the character disp ...

Storing an Array in JSON Format to a File with PHP

{"Files": [ {"file_name": "Text_file.txt","path": "to_folder","file_id": "abc12345"}, {"file_name": "Img.jpg","path": "to_folder" ...

Converting nested JSON data into a Pandas Dataframe: A step-by-step guide

There have been numerous instances of this question being raised, yet none of the solutions seem to work for my specific issue. Query: import urllib, json url = 'https://api.carbonintensity.org.uk/regional' params = 'Accept: application/ ...

What is the best way to prevent an HTML form from being submitted when a user is not logged in, but still allow submission when the user is signed

One of the requirements for users of my application is to be signed in before they can submit form information. Upon clicking on the submit button, my jQuery script verifies if the user is already signed in. If the user is not signed in, an error message ...

What is the most effective method for determining the distance between two UK Postcodes?

Can you suggest a reliable method for calculating the distance between two UK postcodes in order to determine if they are within range? I do not intend to display a map, but instead provide a list of results for valid locations. For example, showing loca ...

What is the best way to transfer a string to a different Vue component?

Within my project, I have a masterData.js file that serves as a repository for my master data. This file retrieves data from my mongo db and distributes it to various components of the project. To facilitate this process, I have implemented a function with ...

Fade effect not working with Bootstrap Modal

I am encountering an issue with the Twitter Bootstrap modal while trying to display post details on WordPress. The problem is that when the modal opens, the entire screen turns grey and nothing in the modal is clickable. I can only exit this mode by pressi ...

Developing a custom JavaScript function to iterate through a group of html elements

In my mission to create a function that loops through a set of HTML elements and gathers their values, I aim to then utilize those values to produce an HTML textarea. Thus far, I've established a series of HTML input boxes and a JavaScript function f ...

Template not rendering array data correctly in Meteor

Here is an example of the array structure: var myarray = [ device1: [ name:device1 , variables: [ variable1: [ name: variable1, unit: "a unit", ...

What could be causing the Bootstrap4 modal to not display data on my Django Template?

Looking for a solution to display data in the modal body using django variables. I'm new to ajax and django, so struggling with it. The ajax function sends the id of the Galeria object, and then the view returns a JsonResponse with the data. Why is th ...

Anime.js: Grid layout causing issues with displaying simple text animations

I'm attempting to create a text animation within a grid layout using the anime.js library, but unfortunately, the animation isn't displaying. The project consists of just one HTML file. The JavaScript code: <script> import anime from &ap ...