Is there a way to delete specific information from a JSON response?

Received the service response in the following format:

Temp([
  {
    XXX: "2",
    YYY: "3",
    ZZZ: "4"
  },
  {
    XXX: "5",
    YYY: "6",
    ZZZ: "7"
  },
  {
    XXX: "1",
    YYY: "2",
    ZZZ: "3"
  }
]);

I need to manipulate this response in JavaScript by removing 'Temp', like so:

[
  {
    XXX: "2",
    YYY: "3",
    ZZZ: "4"
  },
  {
    XXX: "5",
    YYY: "6",
    ZZZ: "7"
  },
  {
    XXX: "1",
    YYY: "2",
    ZZZ: "3"
  }
]

Answer №1

Imagine a scenario where the source providing your JSONP response is trustworthy and consistently delivers accurate JSONP responses.

This essentially means that you will receive a response in the following format:

functionName(jsonString)

Just like in this example:

Temp([{"XXX":"2","YYY":"3","ZZZ":"4"},{"XXX":"5","YYY":"6","ZZZ":"7"},{"XXX":"1","YYY":"2","ZZZ":"3"}])

Extracting JSON - Approach 1

If you only require the object from the response function parameter, you could approach it like this:

var jsonObject = null;
try
{
    var response = 'Temp([{"XXX":"2","YYY":"3","ZZZ":"4"},{"XXX":"5","YYY":"6","ZZZ":"7"},{"XXX":"1","YYY":"2","ZZZ":"3"}])';
    var temp = response.split('(');
    delete temp[0];
    temp = temp.join('(').split(')');
    delete temp[temp.length-1];
    temp = temp.join(')');
    temp = temp.substring(1, temp.length-1);
    jsonObject = JSON.parse(temp);
}
catch(ex)
{
}
console.log(jsonObject);

Extracting JSON - Approach 2 Using this method actually enables handling multiple JSON objects as function parameters. Let's assume you are unaware of the method name the JSONP result is intended to call.

Therefore, we can try something like:

var response = 'Temp([{"XXX":"2","YYY":"3","ZZZ":"4"},{"XXX":"5","YYY":"6","ZZZ":"7"},{"XXX":"1","YYY":"2","ZZZ":"3"}])';
try{
    var fnName = response.split('(')[0];
    var fn = new Function(fnName, response);
    var jsonObject = null;
fn(function(json){
    jsonObject = json;
});
    console.log(jsonObject);
}
catch(ex){
    console.log(ex.message);
}

Answer №2

In my opinion, the provided content does not appear to be a valid JSON response. A correct JSON response should follow this format:

{
"temp": [
    {
        "XXX": "2",
        "YYY": "3",
        "ZZZ": "4"
    },
    {
        "XXX": "5",
        "YYY": "6",
        "ZZZ": "7"
    },
    {
        "XXX": "1",
        "YYY": "2",
        "ZZZ": "3"
    }
  ]
}

To extract the array from this response, you can use the following code:

response["temp"]

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

The connection between the layout of dropdown menus and the way data is handled in forms

I have discovered three different methods for creating dropdowns that can be used in forms: 1) Utilizing HTML with "form-dedicated" attributes such as select and option value="" 2) Implementing the Bootstrap framework with div classes like "dropdown", Butt ...

Convert the solr response to JSON format before returning it

I am trying to retrieve Solr response in JSON format, but I am encountering issues with getting the JSON response. Here is my Solr configuration:' <queryResponseWriter name="json" default="true" class="org.apache.solr.request.JSONResponseWriter"&g ...

Are there more efficient methods than having to include require('mongoose') in each models file?

Is it possible to only require mongoose once in the main app.js file and then pass it to other files without loading it again? Will the script do extra work every time the same module is required? var mongoose = require('mongoose'); I'm wo ...

Update the contents of a div element with JavaScript and PHP combo

When I click on the following div, I want to replace it with a similar one from file.php. The div tag in question is: <div style="display: none;" id="extra" class="container2" xml:id="page"> <div class="title"> <h2>Stuff to check out< ...

Struggling with making JSON.parse() function properly in a Discord Bot

I have a separate JSON file connected like this const Players = require('./Database/Players.json'); and a parser that handles the code client.on('message', message => { if (message.content.toLowerCase() ==='smack activate ...

Is the canvas refusing to disappear?

My HTML5 Canvas element is not disappearing as expected. I wrote a timer function to hide the element when the timer hits 0. I tested this using an alert flag and it worked perfectly. Problem: if (TotalSeconds <= 0) { ctx.clearRect(0, 0, canvas.w ...

Which specific web framework supports the functionalities of Microsoft Dynamics CRM 2011?

Is there an SDK available from Microsoft that can help me create a web product with similar rich ajax features as Microsoft Dynamics CRM 2011? I have considered using Microsoft SharePoint Foundation 2010, but I am concerned that it is designed for small o ...

Divide a collection of objects into groups based on 2-hour time spans

I have an array of objects that I need to split into chunks of 2 hours each, starting on the hour (e.g. 10.00 - 12.00, 12.00 - 14.00, etc). Here is my current solution, but I feel like it may not be the most efficient: Please consider the day variable, w ...

A step-by-step guide on masking (proxying) a WebSocket port

Within my server-side rendering React app, I have set up a proxy for all HTTP calls to a different port. Take a look at the code snippet below for the HTTP proxy configuration. import proxy from "express-http-proxy"; const app = express(); const bodyParse ...

Utilize GSON to encode a collection of objects in a map and ensure the preservation of type

In my coding project, I have defined a class as follows: public class MyClass { private final Map<Property, Object> properties; } The type Property is actually an enum. Imagine that the properties attribute contains two elements: one with a v ...

Incorporating interactive maps into an AngularJS web application

I've been attempting to integrate Google Maps into my AngularJS application, using the script tag below: <script src="https://maps.googleapis.com/maps/api/js?key=[MySecretKeyHere]&callback=initMap" async defer></script> I found this ...

I am looking to concatenate the existing URL with the language segment using jQuery

Looking to update the URL when clicking on a language name? Simply add the current path after the language section. For example, change the URL https://example.com/de_DE/about-us/ to https://example.com/us_EN/about-us/ and vice versa. I attempted this code ...

Managing multiple URLs in a MEAN Stack application

Currently, I'm working on a MEAN stack project to implement a CRUD system for managing courses. One specific aspect that is giving me trouble is figuring out how to handle unique URLs for each course I create. As of now, I am using routeprovider for t ...

Utilizing Vue.js to display raw HTML content in elements.io table

I am trying to display HTML data in a table using Vue.js. new Vue({ el: "#app", data: { todos: [ { text: "<p>Learn JavaScript</p>", done: false }, { text: "<p>Learn Vue</p>", done: false ...

Unable to refresh the view from the controller once the promise has been resolved

On my webpage, I want to display a dynamic list of items that updates whenever the page is refreshed. To achieve this, I am using Parse to store and retrieve my items using promises. Here's a simplified example of how it works: When the index.html pa ...

Understanding the Concept of Getters and Setters in Android Development

Explaining the concept of getter and setter in Android development. Additionally, uncovering the significance of using @Expose in GSON. @SerializedName("url") @Expose private String url; ...

Check for non-null Sequelize Where conditions

Suppose I need to execute a select command using Sequelize with the condition: WHERE ID=2134 However, if the user does not provide an ID, then the WHERE clause should be omitted (as it is null). What is the best way to handle this situation in Sequelize ...

Toggle the visibility of a div by clicking on another div in a

I have created a unique design where a div features a background image of a face, along with a paragraph, two buttons, and an input box inside it. While I know this question has been asked before, my scenario is slightly different. I want the div with the ...

Mastering the use of expressions in ng-click and ng-show in AngularJS

I've been working on creating expandable rows within a table, but I'm encountering some issues. Despite not receiving any error messages, the functionality isn't behaving as expected. I suspect there might be an issue with how I'm using ...

Switching the border of a div that holds a radio button upon being selected

I have a piece of code that I use to select a radio button when clicking anywhere within a div, which represents a product photo. To make it clear for the customer, I want to add a border around the selected product. Here is the initial code: <script t ...