Search code examples
javascriptjsonparsingstringify

JSON parsing and stringify


I am currently working on a Javascript project where I have to parse tons of data. The project requires that I parse some JSON data and bring specific data into another array. Right now, I am using the JSON.stringify method and I can console.log all of the data that I need. The data looks something like this:

{
"type": "FeatureCollection",
"features": [
    {
        "type": "Feature",
        "geometry": {
            "type": "Polygon",
            "coordinates": [
                [
                    [
                        -85.3865810000125,
                        33.90171899971196
                    ],
                    [
                        -85.38659500025622,
                        33.9017919996593
                    ],

yes, this is not all that data-it is about 1200 pages long! I only pasted in the top segment of it. All I really need is how to get to the coordinates aspect of it and into an array. So what I am currently doing is this:

var work = JSON.stringify(response, null, 4)
console.log(work);

Which gives me the above response. However, I am not that familiar with JSON.stringify so if I do:

console.log(work.type);

Attempting to see what the value is for type, I get a response of undefined. Now if I try doing this:

var work = JSON.parse(response)
console.log(work);

I get a response of: VM296:1 Uncaught SyntaxError: Unexpected token o in JSON at position 1

Thus, I cannot get the data parsed which I want to get to which will be the coordinates data. Any help with using stringify would great help me. I have read a lot about how it turns the data into a string but have not really seen a lot about how to parse it. Do I have to use parse? Thank you for your help!


Solution

  • You dont' have to use stringify or parse for this. The response object you are receiving is already a javascript object so you can reference its properties normally

    response.type; // => "FeatureCollection"

    If you try and stringify the response it will lose its type property, for instance:

    typeof "some string".someProperty; // => undefined