I have created one getReports methods in which i am passing my web api get method and able to get the response in json format
Step1
getReports() {
return this._http.get(this.url)
.map((response: Response) => response.json())
.catch(this.handleError);
}
Step2
After this in my component constructor class i am injecting the complete service and under ngOnInit i am subscribing using this.reports.
constructor(private _reportService: GetReports) {
}
ngOnInit() {
this._reportService.getReports().subscribe(reports => this.reports = reports);
}
so in console i am getting the Array with 127 records.My problem is how i can traverse the json data in component so that i will show my nested values
enter image description here
for example while expanding above array i will get data in format of
0
Key 1:" abdef",
Key2 :[1,2,3 ]
key 3:['test','test2']
1
Key 1:" check",
Key2 :[1,2,3 ]
key 3:['test3','test2']
2
Key 1:" ghef",
Key2 :[1,2,3 ]
key 3:['test3','test2']
....
....
....
127
Key 1:" check",
Key2 :[1,2,3 ]
key 3:['test4','test3']
I need to retrieve array value which is collection of the 127 elements like i mentioned above for 0th element I have Key 1 which having value"abdef" .. so first i need to find all the distinct values for Key 1 in 127 elements similarly based on key 1 i need to find all the distinct values which is under Key 3
I need to retrieve all the values belonging to Key 3 based on key1 and also duplicate records will not come .
I went through the links like access key and value of object using *ngFor but it is not fulfilling my requirement.
SO it will be great help if i get the links and responses on How to retrieve or read the nested json data in angular
Get all distinct keys
var distinctKyes = reports.map((a) => a.key1).filter((item, pos, arr) => arr.indexOf(item) === pos);
Fetch all key3 based on key1(value ="abc")
var result = []
myarr.forEach((item) => {
if(item.key1 === "abc"){
result = result.concat(item.key3);
}
})
result = result.filter((item, pos) => result.indexOf(item) === pos);
Related
I have a json data like this
{key:value, key:value, detail:[{key:value, key:value, ...}]}
I want to delete the detail array in this data and throw the remaining elements into another json object, how can I do that?
I tried two ways as below but it doesn't work:
var master =(delivery.deliveryTemp?.toJson() as Map<String, dynamic>).removeWhere((key, value) => key != "detail" || value == null);
var master= delivery.deliveryTemp?.toJson().remove("detail");
This is how I solved it.
var master= delivery.deliveryTemp?.toJson();
master?.removeWhere((key, value) => key=="detail");
I have a List and a dict which need to be compared just by the Keys.
The List is created by Hand for define which Vars will be used in the following process. The List will be used for writing the result in an CSV List = Header.
Some Devices doesn't support all Vars and won't send them Back in the response.
base=["General.IpAddress", "General.ActualHostname", "General.UserLabel1", "General.UserLabel2"]
response_diff='{"general.actualhostname":"ST_38_217","general.ipaddress":"192.168.38.217"}'
As you see the General.UserLabel1 and General.UserLabel2is missing in the response. (There can be missing more vars)
So i have to add to the response the missing Vars with NULL Value.
import json
from pprint import pprint
def compare_ListWithDict(list_base,dict_ref):
#temp dict
dict_base_tmp = {}
dict_ref = dict_ref.lower()
#run thru List an generate an dict with Value 0 for every Key
for item in list_base:
dict_base_tmp[item.lower()] = 0
#load dict_ref as JSON
dict_ref_json=json.loads(dict_ref)
#get len
dict_base_len= len(dict_base_tmp)
dict_ref_len= len(dict_ref_json)
#if lens are equal return the dict_ref (response from Device)
if dict_base_len == dict_ref_len:
return dict_ref_json
else:
#run thru list_base and search for keys they AREN'T in dict_ref_json
#if missing key is found, add the key with Value NULL to the dict_ref_json
for item in list_base:
if not item.lower() in dict_ref_json.keys():
item_lower = item.lower()
dict_ref_json[item_lower]='null'
return dict_ref_json
base=["General.IpAddress", "General.ActualHostname", "General.UserLabel1", "General.UserLabel2"]
response_diff='{"general.actualhostname":"ST_38_217","general.ipaddress":"192.168.38.217"}'
response_equal='{"general.actualhostname":"ST_38_217","general.ipaddress":"192.168.38.217","general.userlabel1":"First Label", "general.userlabel2":"Second Label"}'
Results:
pprint(compare_ListWithDict(base,response_equal))
#base and response are equal by the keys
{'general.actualhostname': 'st_38_217',
'general.ipaddress': '192.168.38.217',
'general.userlabel1': 'first label',
'general.userlabel2': 'second label'}
pprint(compare_ListWithDict(base,response_diff))
#base and response is different by the keys
{'general.actualhostname': 'st_38_217',
'general.ipaddress': '192.168.38.217',
'general.userlabel1': 'null',
'general.userlabel2': 'null'}
I'm request with API REST a JIRA filter since Excel and I return my result in a json object.
I'm parsing this object and I Try to show my result (in a msgbox for now) but I have a problem when the json Key doesn't exist !
A extract of my json :
{
"expand":"schema,names",
"startAt":0,
"maxResults":500,
"total":2,
"issues":[
{
"expand":"operations,versionedRepresentations,editmeta,changelog,renderedFields",
"id":"00001",
"fields":{
"components":[
{
"id":"01",
"name":"component_1"
},
{
"id":"02",
"name":"component_02"
}
]
}
},
{
"expand":"operations,versionedRepresentations,editmeta,changelog,renderedFields",
"id":"00002",
"fields":{
"components":[
]
}
},
]
}
As you cans see, in my first issue (id 00001) I have a 2 components key but in my second issus (id 0002) I don't have component key, because this fields is empty in JIRA for this issue.
So, a part of my code to show my result :
For Each Item In jsonObject("issues")
issueId = Item("id")
compoId1 = Item("fields")("components")(1)("id")
compoId2 = Item("fields")("components")(2)("id")
i = i + 1
'PRINT_OF_MY_RESULT
Next
My problem :
If my issue (00001) has a "component" value, it's OK and I can return my result but ... if my issus (00002) hasn't a result, my code failled to define compoId ... and my code crash.
Did you have a simple solution ? I try somethings with Exists, isEmpty, etc etc ... but nothing concluent for me :(
You can modify your solution some what like this,
For Each Item In jsonObject("issues")
issueId = Item("id")
For Each componentItem In jsonObject(Item("fields")("components"))
If componentItem("id")==1 then
compoId1 = componentItem("id")
EndIf
If componentItem("id")==1 then
compoId2 = componentItem("id")
EndIf
Next
i = i + 1
'PRINT_OF_MY_RESULT
Next
I have a map like so:
[One:[example:value1, example2:value2] ,Two[example 1:value3, example2:value4]]
I'm am matching value1 from a value in another map, but I need to get the keys,either One or Two depending on if it is a match.
So if I say:
if( value1.equals (otherMapValue))
Return One
This map is from a json response so if there is a better way to do this besides a map I can change it. Sorry for the formatting I'm using my phone
This should do:
def someMethod(valueFromOthermap) {
def map = [
One: [example1: 'value1', example2:'value2'],
Two: [example1: 'value3', example2:'value4']
]
map.findResults { k, v ->
valueFromOthermap in v.values() ? k : null
}
}
assert someMethod('value1') == ['One']
If you are looking for the first matching key instead of a list of keys, then use findResult instead of findResults, everything else remains unchanged.
UPDATE:
Regarding JSON to Map parsing, a JSON resonse can be easily parsed to Map as shown below:
Map responseMap = new groovy.json.JsonSlurper().parseText( jsonResponseString )
With the following json
{
"Count":0,
"Message":{
"AppId":0
},
"Data":"[{\"application_name\": \"Grand Central\",\"feature_name\": \"1 Click Fix\",\"access_type_id\": 2,\"member_name\": \"GC_Remote_Support_Security\"},{\"application_name\": \"Grand Central\",\"feature_name\": \"Account Details\",\"access_type_id\": 2,\"member_name\": \"GC_Remote_Support_Security\"},{\"application_name\": \"Grand Central\",\"feature_name\": \"Account Summary\",\"access_type_id\": 2,\"member_name\": \"GC_Remote_Support_Security\"}]"
}
how do I go through the Data array, in the most succinct coding manner possible, to see if any feature_name matches a given string?
Since your JSON contains nested, quoted JSON, you will need nested deserializations using LINQ to JSON to parse your Data array. Having done so, you can use use SelectTokens to query with a JSONPath query to find nested properties named feature_name, then check their value:
var testString = "Account Summary";
var found = JToken.Parse(JObject.Parse(jsonString)["Data"].ToString()).SelectTokens("..feature_name").Any(t => (string)t == testString);
Debug.Assert(found == true); // No assert.
Update
If you want the all JObject with a "feature_name" property matching a given value, you can do:
var foundItems = JToken.Parse(JObject.Parse(jsonString)["Data"].ToString())
.SelectTokens("..feature_name")
.Where(t => (string)t == testString)
.Select(t => t.Ancestors().OfType<JObject>().First()) // Get the immediate parent JObject of the matching value
.ToList();