Reading a particular string object from a JSON string: A guide

Is there a way to retrieve a specific value from the JSON string below? I am trying to extract the nested object "FromUserId": "bd079f57" and then pass it to a Javascript function.

"notification":{
       "title" :"Test",
       "message" : "Message",  
           "android": {
                 "data": {
                         "priority": "2",
                        "profile": "profile",
                        "message": "xxx has sent you a Message.",
                        "style": "inbox",
                        "noteId": "1",
                        "visibility": "1",
                        "title": "Test",
                        "badge": "12",                  
                        "FromUserId": "bd079f57"                            
                        }
                    }
                 }



 "onNotification": function (notification) {         
                        var obj = JSON.parse(notification.message.android.data.FromUserId);  
                      // How do I pass this FromUserId value to the ReadData function?                     
                      ReadData(obj)
                    }
$scope.ReadData(obj){
 //additional processing steps for the JSON data
}

Answer №1

JSON.stringify is a handy function in JavaScript that transforms a data structure into a string.

If you use test.FromUserId, you are referring to the FromUserId property of an object.

When working with your function, make sure you consider the input type carefully. You can either:

  1. (If dealing with an object): Forget about anything related to JSON. Get rid of all functions associated with JSON. or
  2. (If handling a JSON string): Stick to using JSON.parse specifically on notification.

Ensure that you navigate through every layer of your data structure. Ignoring any objects between the top level and your desired data is not possible.

For example, you should access

notification.message.android.data.FromUserId
instead of test.FromUserId.

(If going with case 2, swap notification for test but be sure to access the message.android.data layers explicitly).

Answer №2

To achieve this, you can follow the example below:

"onNotification": function (notification) {         
                        var test = JSON.parse(notification);
                        var obj= test.notification.message.android.data.FromUserId;  
                      // Passing the test.FromUserId to the ReadData function.                     
                      ReadData(obj)
                    }
$scope.ReadData(obj){
 //performing additional operations on the json object
}

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

Using the method .Add within a Jobject to insert a nested element

If I were to have a Json Object: { "data":{ "SomeArray":[ { "name":"test1" }, { "name":"test2" }, { "na ...

Having trouble manipulating DOM elements in Node.js with JSDOM?

Feeling a bit lost here - I'm a newbie to Node JS and I'm attempting to manipulate a DOM element within index.js, my main Node.js file. After reading up on the jsdom module, which supposedly allows you to interact with HTML elements in Node, I t ...

Search for specific item within an array of objects

Working on an Angular project, I am attempting to remove an object from an array. To achieve this, I need to filter the array and then update the storage (specifically, capacitor/storage) with the modified array. Here is my function: deleteArticle(id: str ...

Incorporate just one key from the second JSON file into the primary JSON file using jq

Given: first.json: {"x":10, "y":20} second.json: {"x":15, "z":30} Desired output: { "x": 10, "y": 20 } I am attempting to combine the information from the x key in the second JSON file into the first JSON file, while disregarding any other keys ...

Sort through an array of objects using a different array

I am looking to showcase projects based on specific skills. For instance, if I choose "HTML", I want to see all projects that have "HTML" listed in their array of skills. If I select multiple skills, then only display projects that have those exact skills. ...

Utilizing the append method to extract information from a multidimensional array

I'm currently facing an issue with my code structure. Here is the existing code snippet: .append("Last Name {}, First Name {} Stats: {}".format(result["L_Name"], result["F_Name"], result["Stats"])) The output generated by this code is not exactly wh ...

Selenium web driver showcases its capability by successfully launching the Firefox browser, yet encounters an issue with an invalid address

WebElement searchElement = driver.findElement(By.name("q")); searchElement.sendKeys("Selenium WebDriver"); searchElement.submit(); Displays "Search Results" public static void main(String[] args) { // TODO Auto-generated method st ...

How can jQuery be utilized to dynamically update the text in a navbar?

<div id="page1" data-role="page"> <div data-role="header" data-position="fixed" align="center"><img src="img/VAWE-long-300x30-transparent.png" width="300" height="30" alt="" /></div> <div data-role="content" style="margin ...

How can I use jQuery to automatically redirect to a different HTML page after updating a dynamic label?

When I click on a button in first.html, a function is called to update labels in second.html. However, despite being able to see second.html, I am unable to see the updated values in the labels. Can someone please advise me on how to achieve this? functi ...

Node.js and the Eternal Duo: Forever and Forever-Montior

Currently, I am utilizing forever-monitor to launch a basic HTTP Node Server. However, upon executing the JavaScript code that triggers the forever-monitor scripts, they do not run in the background. As a result, when I end the TTY session, the HTTP server ...

ng-repeat not functioning properly with custom tabs

Everything was working perfectly until I added ng-repeat to the content <ul> <li ng-class="{active:tab===1}"> <a href ng-click="tab = tab==1 ? a : 1">Tab1</a> </li> <l ...

Having trouble sending POST requests in Express?

I developed an API and all the routes were working perfectly until now. However, when I attempted to send a POST request to the "/scammer" route, I encountered the following error message: Error: write EPROTO 1979668328:error:100000f7:SSL routines:OPENSSL_ ...

React Native backhandler malfunctioning - seeking solution

Version react-native-router-flux v4.0.0-beta.31, react-native v0.55.2 Expected outcome The backhandler should respond according to the conditions specified in the backhandler function provided to the Router props. Current behavior Every time the har ...

Can you guide me on utilizing filter in an Apps Script array to retrieve solely the row containing a particular user ID within the cell?

I am using an Apps Script that retrieves data from four different columns in a spreadsheet. However, it currently fetches all the rows instead of just the row that matches the randomly generated 8-digit user ID. function doGet(req) { var doc = Spreadshe ...

Quick method for handling arrays to generate waveforms

I'm currently working on optimizing the code for my web application. While it functions, the performance is a bit slow and I am looking to make improvements: The main concepts behind the code are: The function retrieves the current buffer and conve ...

Determine if the given text matches the name of the individual associated with a specific identification number

Struggling to create a validation system for two sets of fields. There are 6 inputs in total, with 3 designated for entering a name and the other 3 for an ID number. The validation rule is that if an input with name="RE_SignedByID" contains a value, then c ...

Using the arrow keys to navigate through a list of items without using jQuery

Exploring ways to develop a basic autocomplete feature without relying on third-party dependencies has been my recent project. So far, I have managed to populate a results list using an ajax call and complete fields with mouse onclick events for each optio ...

Retrieve JSON data from an API and convert it into a pandas dataframe with duplicate column names

I'm currently working on parsing a json file and I'm having trouble figuring out how to properly break it down into a dataframe. This is the structure of the json I have received from the API: { "result": { "data": [], "totals": [ ...

Exploring the functionality of buttons within jQuery Impromptu

My current project involves creating a survey composition tool. The main focus is on having a preview button that displays the values inputted by the user. <!doctype html> <html> <head> &l ...

Having trouble with Next-Auth's signIn with Credentials feature in NextJS?

I have recently added the next-auth package to my new Next.js project. Despite following all the documentation for both Next.js and next-auth, I am still unable to resolve the issue. The problem I am encountering is as follows: I am trying to log in to my ...