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");
Related
I am trying to drop elements from JSON. Here is my code:
String test = '[{
"type":"new",
"color":"red",
"items": ["aa","bb", "cc"]
}]';
var myJson = jsonDecode(test);
var result = myJson.where((a)=> a != 'items');
print(result);
It does not work. I need to drop items and get:
[{"type":"new","color":"red"}]
In the JSON, test array contains one object item with a property items. Thus, filtering is not caching it.
To remove items, you need to map over items and remove the items key from each.
UPDATED:
var result = myJson.map((a)=> {a.remove('items'); return a;} );
I try to access to my data json file:
[{"id":1,"name":"Maria","project":[{"id":5,"name":"Animals"},{"id":6,"name":"Cats"}]}
This is my approach:
data[0].name;
But like this I get only the result:
Animals
But I would need the result:
Animals, Cats
You are accessing only the name property of 0th index of project array.
To access all object at a time you need to loop over the array.
You can use Array.map for this.
var data = [{"id":1,"name":"Maria","project":[{"id":5,"name":"Animals"},{"id":6,"name":"Cats"}]}]
var out = data[0].project.map(project => project.name).toString()
console.log(out)
If that's your actual data object, then data[0].name would give you "Maria". If I'm reading this right, though, you want to get all the names from the project array. You can use Array.map to do it fairly easily. Note the use of an ES6 arrow function to quickly and easily take in the object and return its name.
var bigObject = [{"id":1,"name":"Maria","project":[{"id":5,"name":"Animals"},{"id":6,"name":"Cats"}]}];
var smallObject = [{"id":5,"name":"Animals"},{"id":6,"name":"Cats"}];
console.log("Getting the names from the full array/data structure: "+bigObject[0].project.map(obj => obj.name))
console.log("Getting the names from just the project array: "+smallObject.map(obj => obj.name))
EDIT: As per your comment on the other answer, you said you needed to use the solution in this function:
"render": function (data, type, row) {if(Array.isArray(data)){return data.name;}}
To achieve this, it looks like you should use my bottom solution of the first snippet like so:
var data = [{"id":5,"name":"Animals"},{"id":6,"name":"Cats"}];
function render(data, type, row){
if(Array.isArray(data)){
return data.map(obj => obj.name);
}
};
console.log("Render returns \""+render(data)+"\" as an array.");
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);
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();
I'm using code from https://github.com/alexholmes/json-mapreduce to read a multi-line json file into an RDD.
var data = sc.newAPIHadoopFile(
filepath,
classOf[MultiLineJsonInputFormat],
classOf[LongWritable],
classOf[Text],
conf)
I printed out the first n elements to check if it was working correctly.
data.take(n).foreach { p =>
val (line, json) = p
println
println(new JSONObject(json.toString).toString(4))
}
However when I try to look at the data, the arrays returned from take don't seem to be correct.
Instead of returning an array of the form
[ data[0], data[1], ... data[n] ]
it is in the form
[ data[n], data[n], ... data[n] ]
Is this an issue with the RDD I've created, or an issue with how I'm trying to print it?
I figured out why take it was returning an array with duplicate values.
As the API mentions:
Note: Because Hadoop's RecordReader class re-uses the same Writable object
for each record, directly caching the returned RDD will create many
references to the same object. If you plan to directly cache Hadoop
writable objects, you should first copy them using a map function.
Therefore in my case it was reusing the same LongWritable and Text objects. For example if I did:
val foo = data.take(5)
foo.map( r => System.identityHashCode(r._1) )
The output was:
Array[Int] = Array(1805824193, 1805824193, 1805824193, 1805824193, 1805824193)
So in order to prevent it from doing this, I simply mapped the reused objects to their respective values:
val data = sc.newAPIHadoopFile(
filepath,
classOf[MultiLineJsonInputFormat],
classOf[LongWritable],
classOf[Text],
conf ).map(p => (p._1.get, p._2.toString))