Anybody experienced with AXIOS? convert response to 'array'

Anybody experienced with AXIOS? convert response to 'array'
0

#1

HELP!

First timer using AXIOS, and what I’m trying to do is make a server-side call, and assign the server response to a JS variable as an array. So that I can pass that array to a function.

I’m running out of ideas on how to make that happen… I can get a response as a “string” from the server, but don’t know if it’s possible to get an array object response from server… I think not. So next option is make the server give out a JSON response, then convert that to an array of objects. But can’t quite figure it out.

In the end, I ended up using eval( ) and that doesn’t seem to be a good idea?

So on my homepage, I have this script.
It works, and produces a map with the correct map markers in the right locations.

    <script>
        var map = new GMaps({
            div: '#map',
            lat: 37.02009820136811,  // center of USA map
            lng: -97.84423828125,
            zoom: 5
        });

        // NOTE:  drop multiple map markers, use an array of marker objects
        axios.get('/api-jobs/LatestJobsMapMarkers.cshtml')
            .then(function (response) {
                eval(response.data);       // <---- BAD IDEA?
                map.addMarkers(moreJobs);
            })
            .catch(function (error) {
                console.log(error);
            });
    </script>

I make a GET call to ‘LatestJobsMapMarkers.cshtml’ and the server returns this string as it’s response… which is then eval( ), and then the map drawn.

var moreJobs = [
    {
        lat: 41.90227704096373,
        lng: -87.9345703125,
        title: 'Chicago, IL',
        infoWindow: {
            content: '<b>Big Data R Programmer</b><br>Chicago, IL'
        }
    },

    {
        lat: 33.10074540514424,
        lng: -116.71875,
        title: 'San Diego, CA',
        infoWindow: {
            content: '<b>Systems Programmer</b><br>San Diego, CA'
        }
    },

    {
        lat: 36.13787471840729,
        lng: -86.8359375,
        title: 'Nashville, TN',
        infoWindow: {
            content: '<b>Web Developer</b><br>Nashville, TN'
        }
    },

    {
        lat: 29.42165652325403,
        lng: -98.48419189453125,
        title: 'San Antonio, TX',
        infoWindow: {
            content: '<b>Data Analyst</b><br>San Antonio, TX'
        }
    },

    {
        lat: 39.740986355883564,
        lng: -104.96337890625,
        title: 'Denver, CO',
        infoWindow: {
            content: '<b>Nodejs Developer</b><br>Denver, CO'
        }
    },

    {
        lat: 36.7498564123657,
        lng: -106.12597456325,
        title: 'MISSING, UK',
        infoWindow: {
            content: '<b>Sample Developer</b><br>Missing, UK'
        }
    },
];

How can I accomplish the same thing without using eval( ) ?


#2

You can easily serialize to JSON in .NET using Newtonsoft. Works a charm.

I’m really confused by what you’re doing here. Is response.data the same as moreJobs? Have you tried JSON.parse? An array is valid JSON, though it’s preferred to use an object instead.


#3

Hey, thanks for the repsonse. I’ll check them out.

Not exactly… but moreJobs gets created and assigned inside the eval( ) operation.

This long string is passed to eval( )

var moreJobs = [
    {
        lat: 41.90227704096373,
        lng: -87.9345703125,
        title: 'Chicago, IL',
        infoWindow: {
            content: '<b>Big Data R Programmer</b><br>Chicago, IL'
        }
    },
....
....

#4

I tried something like

var moreJobs = JSON.parse(response.data.replace('var moreJobs = ','').slice(0,-1))

but because the objects’ properties/values are not surrounded by quotes (for string values), it errors out when it gets to the first property.

    {
        lat: 41.90227704096373,
        lng: -87.9345703125,
        title: 'Chicago, IL',
        infoWindow: {
            content: '<b>Big Data R Programmer</b><br>Chicago, IL'
        }
    }

If the above was:

    {
        "lat": 41.90227704096373,
        "lng": -87.9345703125,
        "title": "Chicago, IL",
        "infoWindow": {
            "content": "<b>Big Data R Programmer</b><br>Chicago, IL"
        }
    }

I think the JSON.parse might have worked.


#5

Originally, the server side response is

[
   { object }, 
   { object }
   ....
]

also tried

{
   { object }, 
   { object }
   ....
}

But console.logging the Axios response.data is always null. I can see the response from the server was correct format in Browser Network tab, but response.data by Axios keeps returning null.

After hours of trying different things, I just went to eval() and had to add the var moreJobs = statement.

Will try that JSON.parse command. I admit, I’m not familiar with that.


#6

I did confirm if the string returned looks like:

var response = `[
    {
        "lat": 41.90227704096373,
        "lng": -87.9345703125,
        "title": "Chicago, IL",
        "infoWindow": {
            "content": "<b>Big Data R Programmer</b><br>Chicago, IL"
        }
    }
]`

var arr = JSON.parse(response)
console.log(typeof arr) // yields "object"

then arr is an array with one object. What I don’t know is how you are going to get the extra quotations marks around the properties.


#7

I’m not familiar with axios but if it doesn’t have to be axios the following may help (fetch API):

fetch('/api-jobs/LatestJobsMapMarkers.cshtml')
    .then((response) => {
        response.json().
            .then((array) => map.addMarkers(moreJons));
    });

I tried it on glitch just now and it seems to be doing what you described. Don’t forget to catch errors! I hope that helps!

EDIT: removed link to glitch demo to avoid broken links as it will be removed.


#8

SOLVED!!!

@PortableStick @RandellDawson @honmanyau
Guys, thank you so much… using all your inputs and clues, I got it working.

Final code for my homepage.

    <script>
        var map = new GMaps({
            div: '#map',
            lat: 37.02009820136811,  // center of USA map
            lng: -97.84423828125,
            zoom: 5
        });


        var mapMarkers;  // <--- wanted to view this in console, so made it global
        // NOTE:  drop multiple map markers, use an array of marker objects
        axios.get('/api-jobs/LatestJobsMapMarkers.cshtml')
            .then(function (response) {
                mapMarkers = JSON.parse(response.data);
                map.addMarkers(mapMarkers);
            })
            .catch(function (error) {
                console.log(error);
            });
    </script>

Gone is the eval( ) command.
Instead, using JSON.parse to convert the response.data to an actual JSON object.

The clincher and where the problem lies was in the server side. So made the following changes to the server side.

@{
    Response.ContentType = "application/json";
    Layout = "";

    var JobLocations = @"[
        {
            ""lat"":
            ""41.90227704096373"",
            ""lng"":
            ""-87.9345703125"",
            ""title"":
            ""Chicago, IL"",
            ""infoWindow"":
            {
                ""content"":
                ""<b>Big Data R Programmer</b><br>Chicago, IL""
            }
        },

        {
            ""lat"":
            ""45.90227704096373"",
            ""lng"":
            ""-89.9345703125"",
            ""title"":
            ""Chicago, IL"",
            ""infoWindow"":
            {
                ""content"":
                ""<b>Big Data R Programmer</b><br>Chicago, IL""
            }
        }
    ]";

}
@Html.Raw(Json.Encode(JobLocations))

I did several things here…
I made the response content-type "application/json"
Then had to construct the array and using quote marks on both the key and data.
Then finally, sending raw output, with a JSON.encode

@Html.Raw(Json.Encode(JobLocations)) 

Now everything works without resorting to the eval( ) hack.

I’m not there yet, but all this data will come from a database so I can just create a loop and build this string.

THANKS AGAIN GUYS… LEARNED A LOT OF NEW THINGS HERE!!!
JSON.parse on the JS side
Json.Encode on the C# server-side