Create a new JSON file to preserve the value of a JSON object

I am working with a JSON file that looks like this:

{
  "soils": [{
    "mukey": "658854",
    "mukeyName": "Meggett-Kenansville-Garcon-Eunola-Blanton-Bigbee (s1517)",
    "sl_source": "Fl soil map",
    "cokey": "3035468",
    "soilName": "Eunola",
    "comppct_r": 20,
    "compArea": "9.96"
  }],
  "asfirs": [{
    "long": -82.96896600817682,
    "lat": 29.977675992923395
  }],
  "polygon": [{
    "rings": [
      [
        [-9235836.910744485,
          3501136.0564117758
        ],
        [-9235798.692230342,
          3500237.921329426
        ],
        [-9236553.507884657,
          3500667.87961353
        ],
        [-9235836.910744485,
          3501136.0564117758
        ]
      ]
    ],
    "spatialReference": {
      "wkid": 102100,
      "latestWkid": 3857
    }
  }]
}

I need to extract the value of the Polygon key and create another JSON object like the one below:

{
  "rings": [
    [
      [-9161396.799823288,
        3453315.140590871
      ],
      [-9160708.866568722,
        3453095.3841345515
      ],
      [-9161349.02668061,
        3452751.4175072685
      ],
      [-9161396.799823288,
        3453315.140590871
      ]
    ]
  ],
  "spatialReference": {
    "wkid": 102100,
    "latestWkid": 3857
  }
}

However, when I try to do this using the code below, I end up with an extra set of brackets [] in the result which is causing issues:

var key3 = 'polygon';
var newPolygonJSON = polygonJson[key3];
var text = JSON.stringify(newPolygonJSON);

The output includes an unnecessary set of brackets as shown below:

[
   {
     "rings": [
       [
         [-9235836.910744485,
           3501136.0564117758
         ],
         [-9235798.692230342,
           3500237.921329426
         ],
         [-9236553.507884657,
           3500667.87961353
         ],
         [-9235836.910744485,
           3501136.0564117758
         ]
       ]
     ],
     "spatialReference": {
       "wkid": 102100,
       "latestWkid": 3857
     }
   }
 ]

I'm looking for a solution to remove these extra brackets and properly extract the value. Any ideas on how to achieve this?

Answer №1

When converting a JSON object to a string, additional [] brackets are added because the object is treated as an array. To extract the JSON from the text variable, you must access the value of the first (and only) element in that array.

var key3 = 'polygon';
var newPolygonJSON = polygonJson[key3];
var text = JSON.stringify(newPolygonJSON[0]);

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

Issue encountered: Unable to add MongoDB object to database

Recently, I have encountered an issue with a script that looks like this: use first_db; advertisers = db.agencies.find( 'my query which returns things correctly ); close first_db; use second_db; db.advertisers.insert(advertisers); This error mess ...

Does JavaScript array filtering and mapping result in a comma between each entry in the array?

The code snippet above showcases a function that retrieves data from a JSON array and appends it onto a webpage inside table elements. //define a function to fetch process status and set icon URL function setServerProcessesServer1761() { var url = "Serv ...

Do we need to use parseInt for the '*' operator in JavaScript?

I have an array where I am mapping it at some point to calculate the sum and percentages. However, when I tried implementing the logic, I noticed that using '*' directly works fine but using '+' adds the two strings together. For exampl ...

Tips for invoking a controller method in HTML code

Hello, I am completely new to AngularJS, HTML, JavaScript, and CSS. Please keep your explanations simple for beginners like me. I'm facing an issue where the function "updateFilterTerm" is not being called, causing the variable "filterTerm" to remain ...

Accessing/Storing Pictures in MongoDB using Mongoose

I've been struggling with managing images in MongoDB for a while now. Everywhere I look suggests using GridFS because of the 16mb size limit per document. However, the documents I want to store are all <16mb each. Currently, I am storing it like th ...

What is the method for performing a spelling check on every property within an array of Objects?

I'm working on a program that takes a user input as an argument and then searches for a similar match in an array of objects. The array of objects is retrieved from a database. When the user inputs a name, the search criteria should find objects with ...

Using an external JavaScript script may encounter difficulties when loading pages with jQuery

Trying to utilize jQuery for loading html posts into the main html page and enabling external scripts to function on them. Utilizing a script (load.js) to load posts into the index.html page: $(document).ready(function () { $('#header').loa ...

How to Incorporate an Anchor Link into a Div as well as its Pseudo Element using CSS, Javascript, or jQuery

How can I make both the menu item and its icon clickable as a link? When either is clicked, the link should work. Here is a CodePen example: http://codepen.io/emilychews/pen/wJrqaR The red square serves as the container for the icon that will be used. ...

Unlocking the Power of Global Props in AlpineJS: A Step-by-Step Guide

I'm currently exploring AlpineJS after having some experience with React and basic knowledge of Vue. One thing that has puzzled me about AlpineJS is how to update a state value from within a function, similar to how it's done in React. Let' ...

Ways to minimize an array of objects by shared key values?

Suppose I have an array of objects structured like this: var jsonData = [ {"DS01":123,"DS02":88888,"DS03":1,"DS04":2,"DS05":3,"DS06":666}, {"DS01":123,"DS02":88888,"DS03":2,"DS04":3,"DS05":4,"DS06":666}, {"DS01":124,"DS02":99999,"DS03":3,"DS04" ...

Transferring JSON data from ActionScript 3 to PHP

I'm having trouble figuring out the issue. I am trying to send JSON data from AS3 to PHP: var sendToPHPJson:String = com.adobe.serialization.json.JSON.encode(sqlResult); myRequest = new URLRequest("http://xxx.pl/FlashFiles/Winebook/uploadToServer.p ...

JavaScript function for searching YouTube videos

While browsing on stackoverflow, I came across the following code snippet: $(document).ready(function () { $("#show").click(function () { getYoutube($("#Search").val()); }); }); function getYoutube(title) { $.ajax({ type: "GET", url: yt_url ...

Disabling dynamic color updates upon refresh

I am currently using chartjs and I want to generate new random colors each time the page is refreshed. However, I need these colors to remain fixed and not change after a page refresh or reload. Below is the function I am working with: getRandomRgb() { ...

Guide on passing variables in a Flutter http.get request

I have been researching Flutter documentation on making http.get requests to retrieve data from a database. However, I only want to fetch specific data by passing a variable in my method. How can I pass this variable 'a' to the server in the foll ...

React Component - Element with an undefined value

When I tried implementing an Ionic Modal as a React Component, I encountered the following error message: Type '({ onClose, tipo }: PropsWithChildren<{ onClose: any; tipo: number; }>) => Element | undefined' is not assignable to type & ...

Images flicker as they transition

Within my HTML body, I have the following: <a id="Hal9000"> In addition, there is a function included: function Hal(MSG){ document.getElementById("Hal9000").innerHTML = "<img src=\"+preloadImage("HAL9000.php?Text="+MSG)+"\"\>" ...

What could be causing the issue with Google Chart in my ASP MVC app?

My controller has a method that returns Json data. [HttpPost] public JsonResult CompanyChart() { var data = db.adusers; var selectUsers = from s in data where (s.Company != null) select s; int f ...

Tips for transferring a variable to another .php file using ajax

Is there a way to pass the id in posts.php using ajax while keeping the href value as "#"? Currently, when I click on this link, it redirects to that link. However, I do not want to navigate to the link and still need to pass the id in posts.php. Any sug ...

What is required to create a basic application that can function offline while featuring an HTML/CSS user interface?

Newbie inquiry: I am interested in creating a small application that can run offline on a desktop computer. The amount of data to be saved is minimal, so I have the option to use a file or some type of database. However, my main question is: What languag ...

Tips for encoding arrays within arrays in JSON from iOS to PHP

When trying to upload an NSArray that has been JSON encoded from NSDictionary to PHP web-services, I encountered an issue. This is how I performed the JSON encoding on my NSArray: NSError * error; NSData * jsonData = [NSJSONSerialization dataWithJSONObje ...