How to parse json lists in flutter - json

How can we parse such type of List data in Flutter? I tried different models but failed. Following is the data:
[
{
"course":"Computer Architecture Fall 2018 - KHI",
"pending_assignment":[
{
"name":"OOAD Project Fall 2018 Section B & D",
"dueDate":"Dec 14, 2018 10:00 pm"
}
]
},
{
"course":"Object Oriented Analysis and Design Fall 2018 - KHI",
"pending_assignment":[
{
"name":"OOAD Project Fall 2018 Section B & D",
"dueDate":"Dec 14, 2018 10:00 pm"
}
]
}
]

As you can check with this website (https://jsonformatter.org/json-parser), that JSON is not valid and contains errors.
For how to parse JSON in general, you can use the json.decode(jsonString); function from the dart:convert package. For more information on that you can check out this site: https://flutter.io/docs/development/data-and-backend/json

Related

Parsing a very complex json response in dart

I'm trying to load a json file from a server response and parsing it in flutter, the model i create is working for all the other fields but i'm in trouble with this class
this is a part of the JSON response:
"episodes": {
"1": [
{
"id": "63",
"episode_num": 1,
"title": "Some Name",
"container_extension": "mp4",
"info": {
"director": "",
"plot": "",
"cast": "",
"rating": "",
"releasedate": "",
"movie_image": "",
"genre": "",
"duration_secs": 6495,
"duration": "01:48:15"
}
}
]
}
in this case the entry under episodes is just one but this will represents a season and all the episode inside it, so under episodes many of this entry (undefined number during coding) can be present
At this time, using online json to dart converter tools i can be able to retrive just this one entry but if a response have more than 1 season i can't see it.
There is any way to handle this?
EDIT:
Solved using a for cicle with max value = (json['episodes'].length + 1).
For the info stored inside each 'episodes' value i can use
json['episodes']['$i']
Valid JSON is always convertible to a Dart data structure. But what you may be asking is "can I get nested objects from this?", and that just depends on how hard you want to work. Some JSON-to-Dart tools are better than others and some JSON values are impossible for any automated tool to make sense of. Only real answer is: "it depends".

Angular - Get this ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed

Decided to find out what all the fuss was about with Angular. Got a demo app working with a JSON file (using db.json and JSON server from the angular CLI). All working great.
So I get adventurous and decide to build a C# API (as that's the long plan anyway).
Straight away I ran into the CORS problem, and to solve in my ASP.NET config I have (startup.cs)
app.UseCors( options =>
{
options
.WithOrigins("http://localhost:4200/")
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
I output my JSON like this (done this like a thousand times in all my apps)
return Json(new { tasks = _context.Tasks });
In my angular app, I have
//private apiUrl = 'http://localhost:5101/tasks'; //<- this is using json server
private apiUrl = "https://localhost:44363/home/tasks"; //<- this is my asp.net api
constructor(private http: HttpClient) {}
getTasks(): Observable<Task[]> {
return this.http.get<Task[]>(this.apiUrl);
}
My web service spits out the exact same JSON (char for char) as the JSON server but in my browser console (after dealing with the cors problem ) I get this:
ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed
I've read lots of articles on here about this error but non seem to deal with this situation, (none that I could find anyway) and I checked a fair few
What am I missing?
This is the JSON
{
"tasks": [
{
"id": 1,
"text": "Doctors Appointment",
"day": "1st January 2022 at 10:30 AM",
"reminder": false
},
{
"id": 2,
"text": "Meeting",
"day": "5th July 2022 at 11:45 AM",
"reminder": false
},
{
"id": 3,
"text": "Car Servicing",
"day": "15th October 2022 at 8:30 AM",
"reminder": false
},
{
"id": 4,
"text": "Cleaner",
"day": "3rd November 2022 at 10:00 AM",
"reminder": false
},
{
"id": 5,
"text": "Dinner",
"day": "6th July 2022 at 7:50 PM",
"reminder": false
}
]
}
Based on your JSON, HttpGet expects to receive the data model as below:
export interface TaskResponse {
tasks: Task[];
}
And with .pipe(map) to return response.tasks as Observable<Task[]>.
import { map } from 'rxjs/operators';
getTasks(): Observable<Task[]> {
return this.http
.get<TaskResponse>(this.apiUrl)
.pipe(map((response: TaskResponse) => response.tasks));
}
Sample Demo on StackBlitz
This error is just because you are trying to loop an object. Just take the data into a result like
this.getTasks().subscribe(result => {
this.data = result.tasks;
})
After taking the response in data you can use the loop.

Monitoring a JSON or YAML config file and showing the parent of the changed attributes

I have a case in which I need to monitor JSON and YAML config files for changes, but all of the solutions that I found only showed line-by-line changes.
For example, if I have a JSON as such:
{
"server-1": {
"name": "A" ,
"metadata":{
"tags": ["X","Y","Z"],
"date-created": "10 March 2021"
}
},
"server-2": {
"name": "B" ,
"metadata":{
"tags": ["W","X","Y"],
"date-created": "11 March 2021"
}
},
}
If server-2's tags were to be changed, I want to get: search-1, metadata, tags as its result.
Does anyone have any ready-to-use solutions that I can use for monitoring purposes?
I am looking for a ready-to-use solutions since the JSON and YAML fields are quite dynamic and contains a lots of fields. I am considering ELK stack or Splunk for this, but I am not quite sure it will work or not.

Manipulate JSON data into cachet.io

I have just set up a Cachet status page but i am struggling to push updates to the components via it's API.
I am looking to take an existing JSON feed from a partner site and use this to update the status on my own page.
Here is a sample of the JSON data I need to pull:
{
"state":"online",
"message":"",
"description":"",
"append":"false",
"status":true,
"time":"Sat 23 Apr 2016 10:51:23 AM UTC +0000"
}
and below is the format Cachet uses in it's API.
{
"data": {
"id": 1,
"name": "Component Name",
"description": "Description",
"link": "",
"status": 1,
"order": 0,
"group_id": 0,
"created_at": "2015-08-01 12:00:00",
"updated_at": "2015-08-01 12:00:00",
"deleted_at": null,
"status_name": "Operational"
}
}
Never dealt with JSON stuff before, but I guess i need a script that i can run every X mins to grab the original data and do the following:
Convert the "state" from the original feed into Cachet ones.
Update the "updated_at" time with the time the script was last run.
Any help or tutorial's would be really appreciated.
Thanks!
I'm the Lead Developer of Cachet, thanks for trying it out!
All you need to do is update the Component status. Cachet will take care of the updated_at timestamp for you.
I'm unable to write the script for you, but you'd do something like this:
// This will be a lookup of the states from the service you're watching to Cachet.
serviceStates = [
'online' => 1,
'issues' => 2,
'offline' => 4,
]
// The id of the component we're updating
componentId = 1
// The state that is coming back from the service you're watching
state = 'online'
request({url: 'demo.cachethq.io/api/v1/components/'+componentId, data: { status: serviceStates[state] }})
Pseudo code, but you should be able to work from that.

how to convert the Elasticsearch json output in a table?

I'm using Head plugin for ELASTICSEARCH for running queries.
I want to convert in a table the output of the query.
The part that I need is just the "hits" object array
where the columns are the fields that I have specified into the query:
"http.date","src_shift","#timestamp","src_tz".
is there any tool or plugin to do that?
below a brief output of query:
"took": 2418,
"timed_out": false,
"_shards": {
"total": 3503,
"successful": 3503,
"failed": 0
},
"hits": {
"total": 2524,"max_score": 9.194927,"hits": [
{
"_index": "$002555","_type": "pcap","_id": "AVAJJphp2MeWtoWCbQYG","_score": 9.194927,"fields": {
"src_shift": [
1],"http.date": [
"Fri, 12 Jun 2015 22:40:54 GMT"],"#timestamp": [
1434147980397],"src_tz": [
"Europe/Warsaw"]}},{
"_index": "$002555","_type": "pcap","_id": "AVAJJphp2MeWtoWCbQYH","_score": 9.194927,"fields": {
"src_shift": [
1],"http.date": [
"Fri, 12 Jun 2015 22:40:54 GMT"],"#timestamp": [
1434147980397],"src_tz": [
"Europe/Warsaw"]}},...
In the head plugin, on your Any Request tab, you can use the Result Transformer section located just below the Query section. By default it returns the whole JSON response.
You can modify that and massage the response to return whatever you want. In your case, if you replace the default return root; by the code below, you'll get what you want:
return root.hits.hits.map(function(hit) {
var values = [];
for (var field in hit.fields) {
values.push(hit.fields[field]);
}
return values.join(",");
});
The output should be
1,"Fri, 12 Jun 2015 22:40:54 GMT",1434147980397,"Europe/Warsaw"
1,"Fri, 12 Jun 2015 22:40:54 GMT",1434147980397,"Europe/Warsaw"
...
There's a utility in Kibana called tabify that converts ElasticSearch results into tabular form. You can find its implementation here: https://github.com/elastic/kibana/blob/master/src/ui/public/agg_response/tabify/tabify.js