decoding JSON without the need for jQuery

Is there a way to convert the result retrieved from an ajax call into a JavaScript array without relying on jQuery?

Alternatively, would it suffice to simply loop through the JSON array without converting it into a JavaScript array?

Currently, I just need to display the results obtained from the ASMX service. Using jQuery is not an option.

Data received from the request:

string xmlns="http://tempuri.org/"
[{"Action":"Test1","Target":"#cTarget","Payload":"Hello"},{"Action":"Test2","Target":"#cTarget","Payload":"World"}]
string

      [
           {
                 "Action":"Test1",
                 "Target":"#cTarget",
                 "Payload":"Hello"
           },         
           {
                 "Action":"Test2",
                 "Target":"#cTarget",
                 "Payload":"World"
           }
      ]

JavaScript Code

  var httpRequest;

    function makeRequest(url, input) {
        if (window.XMLHttpRequest) { // Mozilla, Safari, ...
            httpRequest = new XMLHttpRequest();
        } else if (window.ActiveXObject) { // IE
            try {
                httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
            } 
            catch (e) {
                try {
                    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } 
                catch (e) {}
            }
        }

        if (!httpRequest) {
            alert('Giving up :( Cannot create an XMLHTTP instance');
            return false;
        }
        httpRequest.onreadystatechange = function(){
            if (httpRequest.readyState === 4) {
                if (httpRequest.status === 200) {
                    var results = httpRequest.responseText;
                        var asJavaScriptArray = JSON.parse(results);

                    }
                }
            //}
        };

        httpRequest.open('POST', url);
        httpRequest.setRequestHeader('Content-Type', 'application/json');
        httpRequest.send(input);
    }

    var endpointAddress = "Core/RecipeDemo.asmx";
    var url = endpointAddress + "/Base";
    makeRequest(url, "{}");`

C# Code

[System.Web.Script.Services.ScriptService]
public class RecipeDemo : System.Web.Services.WebService
{

    [WebMethod]
    public string Base()
    {

        List<Recipe> listOfRecipe = new List<Recipe>();
        JavaScriptSerializer  jss = new JavaScriptSerializer();

        listOfRecipe.Add(new Recipe {Action = "Test1", Payload = "Hello", Target = "#cTarget"});
        listOfRecipe.Add(new Recipe {Action = "Test2", Payload = "World", Target = "#cTarget"});

        return jss.Serialize(listOfRecipe);
                }
}

Answer №2

Did you know that JSON is actually a subset of JavaScript?

This means that converting a JSON string into a JavaScript object is quite simple:

var jsonData = FetchDataFromServer() ;
var parsedObject = eval( '(' + jsonData + ')' ) ;

It's important to be cautious when using the eval function, especially with untrusted sources, as it can execute any JavaScript code. You can learn more about this at http://www.json.org/js.html.

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

Enhancing the Ext.ux.grid.RowEditor by implementing tooltips for the save and cancel buttons

I am looking to implement tooltip messages for the save and cancel buttons in Ext.ux.grid.RowEditor. For example, I want the save button to have a tooltip that says "Save the records" and the cancel button to have a tooltip that says "Cancel saving the rec ...

Struggling to properly interpret intricate JSON data using Gson

As a newcomer, I am attempting to analyze the json data from Riot's League of Legends, but I am struggling with the complexity of it. I am hoping that someone could offer assistance. Here is a snippet of the json data: { "type": "champion", "version ...

tips for changing a json string into yaml format

I am facing an issue with the given code snippet: string stringXDoc = JsonConvert.SerializeObject(ConnectedItemOperations.GetConnectedItemById(id).Edits.EditableData); var json = JsonConvert.DeserializeObject(stringXDoc); The specific file is triggeri ...

Troubleshooting issue with Onchange in select HTML element within Django

I'm working with a Problems model in my project. In my Models file models.py class Problems(models.Model): Easy = 'Easy' Medium = 'Medium' Hard = 'Hard' NA = 'NA' DIFFICULTY = [ (NA ...

Adding a class to the body element in an HTML file using AngularJS

Greetings! Currently I am in the process of developing a web application using AngularJS SPA, which supports both English and Arabic languages. I am facing an issue with adding RTL and LTR properties by applying classes to the body HTML element in my app.j ...

Launching a modal in a new browser window with the help of JavaScript or PHP

I need to implement a feature where clicking a link opens a modal in a new tab and redirects the current page to a different link, similar to how retailmenot handles coupons. Here is the code snippet I am currently working with: <div onClick="myFunctio ...

What is the best way to remove a class from an element upon successful completion?

How can I make an image disappear when the user clicks a button in the associated form? I'm struggling to implement this feature. Any suggestions? <script type="text/javascript"> $(document).ready(function() { $(".removebutton").s ...

Discover the effective approach for executing JMeter to effortlessly display the absent elements

I have two separate GET APIs that return response codes containing an ID number and a corresponding title. For API_1, here are some sample responses (with 100 IDs): { "result": "OK", "obj": { "list" : [ { "id" : 9 ...

Do the items appear on screen only once you start typing in AngularJS?

Most things are working well except for a couple of issues Code var app = angular.module("MyApp", []); app.filter('offset', function() { return function(input, start) { start = parseInt(start, 10); return input.slice(start); }; } ...

Increase the duration of the asp.net session timeout to a full 24 hours

Currently, I am working on developing an ASP web application and a website using webforms. Within the application, I have 3 to 4 sessions set up, including Session["Rate"], Session["webinformation"], and Session["userinformation"]. The issue I am facing ...

Endless loop in React Native with an array of objects using the useEffect hook

For the current project I am working on, I am facing the challenge of retrieving selected items from a Flatlist and passing them to the parent component. To tackle this issue, I have initialized a local state as follows: const [myState, setMyState] = useS ...

Obtain the text content of a div using JavaScript

Hello, I am new to Javascript! I have a table structure that looks like this: <table id='master_tbl'> <tbody> <tr id="master_hr'> <td class="myclass"> <table> <tbody ...

Encountered an issue during the installation of react router - in need of assistance to resolve the error

Encountering an Error Error Message when Installing React Router DOM: npm WARN: The use of global `--global` and `--local` is deprecated. Use `--location=global` instead. npm ERR! code EPERM npm ERR! syscall mkdir npm ERR! path D:\ npm ERR! errno -404 ...

Why isn't the onChange function triggering in the input type text when the input is not manually typed in?

I am currently facing an issue with two text fields in my HTML form. Here is how they are set up: HTML : <input type="text" id="input1" onchange="doSomething();" disabled/> <input type="text" id="input2"/> JavaScript : function doSomething( ...

Querying data with parameters in a client-side rendered application with Next.js

Currently, I am developing a chat application using Next.js and Axios. One of the functionalities I implemented is a dynamic route called chat/:pid to fetch data using the provided pid. However, I encountered an issue where the values are coming back as un ...

Enhance my code to eliminate repetitive elements

Check out this unique plant array: export const uniquePlants = [ { name: 'monstera', category: 'classique', id: '1ed' }, { name: 'ficus lyrata&ap ...

You are unable to insert a variable within the channels.get() method in discord.js

Attempting to troubleshoot this issue has been quite frustrating. Despite my efforts, it seems that something is not working as expected. I can't help but wonder if I am simply overlooking a simple mistake due to fatigue. Here's the scenario: It ...

What is the best way to return information from a Xamarin.iOS UITableView to the main page?

I am a beginner in Xamarin.iOS and may not be asking my question correctly. In my project, I have a button on an upload page that, when clicked, navigates to a UITableView page. The user can choose a row in the table, and then return to the upload page. ...

Sequelize error: Foreign key mentioned, yet not found in the table

I recently started using Sequelize and have been relying heavily on the documentation available here. The documentation mentions the importance of using hasOne(), hasMany(), and belongsTo() to automatically add foreign key constraints. In my case, I am wor ...

Simplify JSON data using Jq and include array index in the final output

I'm currently working on consolidating a nested JSON structure into a single JSON output: { "Id" : "1", "items" : [ {"item_name" : "shirt","value" : 10}, {"item_n ...