get json root key based on value - json

{
"vitals": {
"title": "Vitals IR",
"name": "vitalsIr",
"formid":"5ed5f7ca158a91827891cab2"
},
"anthropometry": {
"title": "Anthropometry IR",
"name": "anthropometryIr",
"formid":"5ed621ac158a91228191cafd"
}}
How to get the root key name vitals , anthropometry based on formid value
for example if formid value is "5ed621ac158a91228191cafd"
I need output as anthropometry need to achieve this in angular javascript

To loop through a json object using JavaScript, you can preform a for on the keys. E.g for (jsonPropertyName in json) { ... }. You can then query the formId.
For example:
function ProvideRootKey(formId) {
var results;
for (jsonPropertyName in json) {
if (json[jsonPropertyName]['formid'] === formId) {
results = jsonPropertyName
}
}
return results
}
var json = JSON.parse('{ "vitals":{ "title":"Vitals IR", "name":"vitalsIr","formid":"5ed5f7ca158a91827891cab2"}, "anthropometry":{ "title":"Anthropometry IR", "name":"anthropometryIr", "formid":"5ed621ac158a91228191cafd"}}');
console.log(ProvideRootKey('5ed621ac158a91228191cafd'))
Output (in console log):
"anthropometry"
See working example: https://jsfiddle.net/vgo81stm/1/

Related

How to search in json object in angular using a string?

Json
{
"rootData": {
"test1": {
"testData0": "Previous data",
"testData1": "Earlier Data"
},
"test2": {
"testData0": "Partial data",
"testData1": "Services data"
},
"test3": {
"testData0": "Regular data",
"testData1": {
"testData0": "Your package"
}
}
}
}
Component.ts
import * as configData from './myData.json';
getData(data: string){
console.log(configData.rootData.test1.testData0); //returns "Previous Data.
return configData.rootData.{{data}}.testData0;
}
This getData method is being called in a loop passing a string with values of "test1" the first time "test2" the second time and "test3" the third time called.
I want to do something like this
return configData.rootData.{{data}}.testData0; //should return Previous data, then "partial data" if called again because test2 will be passed in data string.
I know this is not possible the way I am doing it because {{data}} is not defined in my json object.
The goal is to check for the object inside the object. The string data is returning values existing in the json object. I want to use that data to dynamically search in the json file and pull the values.
I know my attempt is not valid. I would like to know if there is an alternative to make this work as I intended.
To get the value with the key in Object, you can use Object[key] (here, key is variable name) and this will return the value of the selected key.
return configData.rootData[data]?.testData0; // Javascript case
So instead of using {{ }}, replace it with square brackets and you will get the result.
And on the above code, rootData[data]?.testData0 has same meaning as rootData[data] ? rootData[data].testData0 : undefined so this will be needed for validation check. (unexpected data value input)
On Typescript,
if (data in configData.rootData && "testData0" in configData.rootData[data]) {
return configData.rootData[data].testData0;
} else {
return undefined;
}
const input = {
"rootData": {
"test1": {
"testData0": "Previous data",
"testData1": "Earlier Data"
},
"test2": {
"testData0": "Partial data",
"testData1": "Services data"
},
"test3": {
"testData0": "Regular data",
"testData1": {
"testData0": "Your package"
}
}
}
};
let data = 'test1';
console.log(input.rootData[data]?.testData0);
data = 'test2';
console.log(input.rootData[data]?.testData0);
data = 'test3';
console.log(input.rootData[data]?.testData0);
data = 'test4';
console.log(input.rootData[data]?.testData0);
data = 'test5';
if (data in input.rootData) {
console.log('Existed', input.rootData[data].testData0);
} else {
console.log('Not Existed');
}
I use ng2-search-filter.
By directive
<tr *ngFor="let data of configData | filter:searchText">
<td>{{testData0}}</td>
<td>{{testData1}}</td>
...
</tr>
Or programmatically
let configDataFiltered = new Ng2SearchPipe().transform(this.configData, searchText);
Practical example: https://angular-search-filter.stackblitz.io

Remove a specific JSONObject from JSONArray in groovy

Say I have a JSON request payload like
{
"workflow": {
"approvalStore": {
"sessionInfo": {
"user": "baduser"
},
"guardType": "Transaction"
}
}
}
I get the value of user via
def user = req.get("workflow").get("approvalStore").get("sessionInfo").get("user")
Now, I get a RestResponse approvalList which I store as list and return to caller as return approvalList.json as JSON. All well so far.
Suppose the response (approvalList.json) looks like below JSONArray -
[
{
"objId": "abc2",
"maker": "baduser"
},
{
"objId": "abc1",
"maker": "baduser"
},
{
"objId": "abc4",
"maker": "gooduser"
}
]
Question : How may I filter the approvalList.json so that it doesn't contain entries (objects) that have "maker": "baduser" ? The value passed to maker should essentially be the user variable I got earlier.
Ideal required output -
It's not entirely clear if you always want a single object returned or a list of objects but using collect is going to be the key here:
// given this list
List approvalList = [
[objId: "abc2", maker: "baduser"],
[objId: "abc1", maker: "baduser"],
[objId: "abc4", maker: "gooduser"]
]
// you mentioned you wanted to match a specific user
String user = "baduser"
List filteredList = approvalList.findAll{ it.maker != user}​​​​​​
// wasn't sure if you wanted a single object or a list...
if (filteredList.size() == 1) {
return filteredList[0] as JSON
} else {
return filteredList as JSON
}​
Pretty simple. First parse the JSON into an object, then walk through and test.
JSONObject json = JSON.parse(text)
json.each(){ it ->
it.each(){ k,v ->
if(v=='baduser'){
// throw exception or something
}
}
}

How to access data inside a complex JSON object in Dart?

I use a WebSocket to communicate to a server in my Flutter app. Let's say I receive a JSON object trough the WebSocket :
{
"action": "getProduct",
"cbackid": 1521474231306,
"datas": {
"product": {
"Actif": 1,
"AfficheQte": 0,
"Article": "6"
},
"result": "success"
},
"deviceID": "4340a8fdc126bb59"
}
I have no idea what the content of datas will be until I read the action, and even then, it's not guaranteed to be the same every time. One example of a changing action/datas is when the product doesn't exist.
I can parse it in a Map<String, Object>, but then, how do I access what's inside the Object?
What's the correct way to read this data?
Not sure what the question is about, but you can check the type of the values and then continue accordingly
if(json['action'] == 'getProduct') {
var datas = json['datas'];
if(datas is List) {
var items = datas as List;
for(var item in items) {
print('list item: $item');
}
} else if (datas is Map) {
var items = datas as Map;
for(var key in items.keys) {
print('map item: $key, ${items[key]}');
}
} else if(datas is String) {
print('datas: $datas');
} // ... similar for all other possible types like `int`, `double`, `bool`, ...
}
You also can make that recursive to check list or map values if they are String, ...

Taking out a text from a String as a Key from Json

I need to take out 1000 from this Key-Value Pair in node Js
"msg":"amamm : ErrorResponse {\"abcd1\":{\"Status\":\"E\",\"rem\":{\"Code\":\"1000\",\"message\":\"Unable to access your information at this time.(1000)\"}}}"
The JSON what you have posted is invalid. May be your JSON should be like the following:
var json = {
"msg": {
"amm": {
"ErrorResponse": {
"abcd1": {
"Status": "E",
"rem": {
"Code": "1000",
"message": "Unabletoaccessyourinformationatthistime.(1000)"
}
}
}
}
}
}
Then in node.js you have get the value using dot notation like as follows:
json.msg.amm.ErrorResponse.abcd1.rem.code
Will give you the value 1000
Assuming you can get the string
amamm : ErrorResponse {\"abcd1\":{\"Status\":\"E\",\"rem\":{\"Code\":\"1000\",\"message\":\"Unable to access your information at this time.(1000)\"}}}
by doing err.msg
You can get the json and then get the string you want. I copied the content of the msg into a variable str just to test the regex
var re = /\{.*?\}$/;
var str = 'amamm : ErrorResponse {\"abcd1\":{\"Status\":\"E\",\"rem\":{\"Code\":\"1000\",\"message\":\"Unable to access your information at this time.(1000)\"}}}';
var m;
if ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
var content = JSON.parse(m[0]);
console.log(content);
console.log(content.abcd1.rem.Code);
}
Here's a working example: http://jsfiddle.net/sger1gk6/

AngularJS - Filtering Json by a variable

I am working on a single page app using dynamic routing. I get my bookid from the URL as below
myApp.controller('BookCtrl', function($scope,$routeParams) {
$scope.mybookid=$routeParams.bookurl;
});
Here is my data
var bookdata = {
"records": [
{
"seriesid": "SpectrumSeries",
"name": "White Curse",
"bookid": "WhiteCurse",
"image": "book1",
}
...
]};
In the above controller, how to I filter out an object that has bookid that equals to $scope.mybookid? I know I can do this by ng-repeat and filter but is there a more efficient way?
Use filter in javascript:
var filteredBooks = bookdata.records.filter(function(book){
return book.bookid == $scope.mybookid;
});
The filteredBooks array will contains all the book with your bookId.