Tips for retrieving a unique key from a JSON object response

Display the object_id for each object(response) in the provided dataset.

This is the response obtained from an API. Any suggestions or solutions are greatly appreciated.


response:{"object_id":"a9951ef0","datetime":"2019-03-20T04:59:23.001Z","ignition_status":"ON"}

response:{"object_id":"8b1546924063","datetime":"2019-03-20T04:59:23.001Z","ignition_status":"OFF"}

response:{"object_id":"9b9d","datetime":"2019-03-20T04:59:23.001Z","ignition_status":"ONLINE"}

Desired output :

  1. object_id = a9951ef0

  2. object_id = 8b1546924063

  3. object_id = 9b9d

Answer №1

If you have three responses with a common key and need to extract the value of that key, consider using streams.

Start by converting the JSON responses into a List of objects:

[
  "response1",
  "response2",
  "response3"
]

arrayList = new Gson().fromJson(<above json>, ArrayList.class)

Then, retrieve the desired values using streams:

arrayList.stream.map(<arraylistType> :: <keyName>).collect(Collectors.toList());

Answer №2

Your API is sending back JSON data, which is in the form of a string. In order to work with this data, you will need to "convert" it into a JavaScript Object using the parse method. Once parsed, you can easily access the value associated with a specific key.

const parsedResponse = JSON.parse(response);
console.log(parsedResponse.object_id);

Answer №3

To tackle this issue, consider the following approach outlined in pseudo code form (please note that it may require some adjustment to fit your specific scenario).

# Begin by obtaining the response from the API and converting it into an array, using newline characters as separators (feel free to use a different separator if necessary).
responses_in_array = real_response.split("\n");

# Iterate through each response within the array.
foreach(single_response in responses_in_array) {

    # Prior to converting responses into JavaScript objects, make sure to clean them up appropriately.
    clean_response = single_response.replace("response:", "");
    real_object = JSON.Parse(clean_response);

    // Perform any desired actions. Should you need to access object_id, simply refer to
    // real_object.object_id.
    //
    // Additionally, consider checking for empty lines before cleaning or processing them.

}

Once you have successfully implemented the fundamental logic for parsing the message, explore alternative methods or utilize built-in functions to enhance your solution further.

Answer №4

Resolved: I managed to fix the issue using the method outlined below, and now everything is running smoothly.

     <script type="text/javascript">
       document.getElementById('test').onclick = function() {
         xhr = new XMLHttpRequest();
         xhr.open("GET", "filename.json or api url", true);
         //xhr.open("GET", "compose.json", true);
         xhr.onprogress = function(e) {
           var data = e.currentTarget.responseText;
           console.clear();
           var formattedData = JSON.parse(JSON.stringify(data))
                                .replace(/(\r\n|\n|\r)/gm, "#")
                                .replace(/##response:/g, ",")
                                .replace(/response:/g, "")
                                .replace(/##/g, "")
                                .replace(/\\n/g, "\\n")  
                                .replace(/\\'/g, "\\'")
                                .replace(/\\"/g, '\\"')
                                .replace(/\\&/g, "\\&")
                                .replace(/\\r/g, "\\r")
                                .replace(/\\t/g, "\\t")
                                .replace(/\\b/g, "\\b")
                                .replace(/\\f/g, "\\f");
            // remove non-printable and other non-valid JSON characters
            formattedData = "["+formattedData.replace(/[\u0000-\u0019]+/g,"")+"]"; 
            var finalData = JSON.parse(formattedData);

            console.log(finalData);              
         }
         xhr.onreadystatechange = function() {
           if (xhr.readyState == 4) {
             console.log("Completed = " + xhr.responseText);
           }
         }
         xhr.send();
       };
     </script>

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

When deploying a model on Databricks experiment, the content type parameters for the format are not being recognized

While attempting to serve a model in Databricks using MLflow, I encountered the following error: Unrecognized content type parameters: format. IMPORTANT: The MLflow Model scoring protocol has changed in MLflow version 2.0. If you are seeing this error, y ...

What is the best way to incorporate a new item into Redux with a nested data structure similar to this? Specifically, I am looking to add new

Seeking assistance with dynamically pushing new items to a deeply nested choice array in order to render react native TextInput components using the map function. Below, you will find details on the data structure, reducer design, and other relevant code s ...

Is it possible to create a mapping for virtual directories containing *.asmx methods in ASP.Net 2.0?

Not long ago, I successfully configured WebServices to return both JSON and XML from the ASPX code-behind. Today, I faced a new challenge of migrating an existing ASMX WebService to return JSON instead of XML. After creating a new method in the ASMX code- ...

Leverage the power of lodash or es6 by creating a custom function that accepts an object containing deeply nested properties and outputs a new object containing only specific properties

I have a complex object with unnecessary properties and deeply nested values that I need to filter. My objective is to transform this initial object into a new object containing only the specific fields I require. Here's an illustration of the large ...

There was an error during product validation that occurred in the userId field. In the Node.js application, it is required to

I am in the process of developing a small shop application using node.js, express, and mongoose. However, I have encountered an issue when attempting to send data to the MongoDB database via mongoose. Here is the product class I have created: const mongoo ...

`Erase content from a field once text is typed into a different field`

I have a Currency Converter with two input fields and a button. I enter the amount to be converted in the first field, and the result of the conversion appears in the second field. My question is: How can I automatically clear the second field when I type ...

Adjusting the gap between TableRows in Material-UI

Is there a way to increase the spacing between TableRow MaterialUI components in my code? <S.MainTable> <TableBody> {rows.map(row => { return ( <S.StyledTableRow key={row.id}> <TableCell component="th" s ...

Transform an item into JSON format, and proceed to save the resulting JSON as a downloadable text file within an Asp.net core application

Exploring Data and Code: I am currently working on a User Interface that allows users to customize an object according to their requirements. The ultimate goal is to enable them to download a file containing the JSON representation of this customized obje ...

Is there a way to extract the content length from the raw DraftJS data?

I have a system where I am storing the data from my DraftJS editor in my database as a JSON string by passing it through convertToRaw(editorState.getCurrentContent()). For example, this is how the stored data looks like in the database: {"blocks": [{"key ...

Matching numbers that begin with zero or are completely optional using Regex

Attempting to come up with a regex pattern that will allow the entry of the specified input into an HTML input field: The input must begin with 0 The input can be left empty and characters may be deleted by the user ^[^1-9]{0,1}[0-9\\s-\& ...

Rendering items in a list with React does not just display the last item on the list

I encountered an issue where, when I retrieve data from an API and add it to the state's array, I only see the last list item even though the mapping process is supposed to include more than 1 item. const [items, setItems] = useState([]); con ...

Creating a React Component in TypeScript that utilizes Promise Objects for data handling

After receiving a Promise type Object as a response, an error has been encountered: Error: Objects are not valid as a React child (found: object with keys { key1, key2, key3 ...}... How can this issue be resolved? // Component.tsx import React, { us ...

Retrieve the initial link value in jQuery and make changes to it

Is there a way in jQuery to append to the current value of an attribute without storing it in a variable first? For example: $(document).ready(function() { $("#btn").click(function() { // get the link currently var linkCurrent = $("#link").att ...

export module from the express framework

function affirm(){ console.log("yes") } Element={} Element=affirm Element.something="something" Element.nothing="nothing" DEPICTED IN WEB BROWSER: In the code snippet above, if you were to console.log(Element), it would display ...

The comparison between local variables and data can result in a significant drop in performance

My current project involves VueJS and Cesium, but I'm facing a performance issue with a significant drop in frame rate. While I have identified the problem area, I am unsure of why this is happening and how to resolve it. export default { name: ...

Retrieve information from Node.js using Express

I am working on a server with Node.js and using Express to create a web application. I have successfully implemented a function called rss_interrogDB that retrieves an array from a database. Now, I am trying to use this array to display a list on the HTML ...

Developing an if-else statement to showcase a different div depending on the URL

Having trouble with an if/else statement to display one div or another based on the URL: No matter what I try, only "Div 1" keeps showing. Here's my code snippet: <script> if (window.location.href.indexOf("pink") > -1) { document.getElemen ...

How to create a floating <Toolbar/> with ReactJS, Redux, and Material-UI

Can anyone help me figure out how to make a toolbar floatable when scrolling down using Material-UI? I tried setting textAlign:'center', position: 'fixed', top: 0, but it's resizing strangely when applied to the <Toolbar/>. ...

what is the process for creating a dynamic display slide in bxslider?

I am trying to create a flexible length display using bxSlider. Here is the code I have so far. JS var duration = $('ul > li > img').data("bekleme"); $(document).ready(function () { $('.bxslider').bxSlider({ ...

Output the variables within a jade template

Is there a way to display a default value inside a textarea in my form using the code below? textarea(class="form-control", name="details") if restaurant.details #{restaurant.details} However, when the value (restaurant.details) is set, i ...