jsondecode loading issue in dart - json

I try to run below code in flutter App but it loads half JSON data, same API when running for a web app it works fine.
Any idea how to solve this issue?
Example
Future <List> test() async{
final response = await http.post(
"https://xyz/allData",
body: jsonEncode({
"email": "email"
}),
headers: {
HttpHeaders.contentTypeHeader: ContentType.json.toString(),
HttpHeaders.authorizationHeader: token
});
final data= json.decode(response.body);
OR
Map<String, dynamic> data =json.decode(response.body);
Error
half JSON fetch by above code
below content I recieved :
{success: true, msg: Loaded, content:
{total: 3, on: 0, off: 3,
on: {},
off: {
11: {id: 11, last_data: N/A,value: {N/A: {name: N/A, value: N/A}},
name: 01, type: temp, upper: 20, lower: 10, email: [], phn_list: [], id: 01,status: 0, freq: 10, description: 01, status_notf: 0, lat_map: 0, lng_map: 0, html: html},
12: {id: 12, last_data: N/A, value: {N/A: {name: N/A, value: N/A}},
name: 02, type: temp, upper: 20, lower: 10, email: [], phn_list: [], id: 02, status: 0,freq: 10, description: 02, status_notf: 0, lat_map: 0, lng_map

Related

How to left join two json array based on common id using RxJS

Need help on a problem with Rxjs join.
I have two observables with common id, I want to perform join to show records
from both objects based on id.
let emp = of([
{ id: 1, name: 'aa', age: 20 },
{ id: 2, name: 'bb', age: 21 },
{ id: 3, name: 'cc', age: 22 },
{ id: 4, name: 'dd', age: 23 }
]);
let details = of([
{ id: 1, address: 'ee' },
{ id: 1, address: 'ff' },
{ id: 2, address: 'gg' },
{ id: 2, address: 'hh' }
]);
I need the join like this:
[
{id: 1, name: 'aa', age: 20, details: [{address: 'ee'},{address: 'ff'}] },
{id: 2, name: 'bb', age: 21, details: [{address: 'gg'},{address: 'hh'}] },
{id: 3, name: 'cc', age: 22, details: undefined },
{id: 4, name: 'dd', age: 23, details: undefined },
]
I have tried like this:
forkJoin([emp, details]).pipe(
map(([_emp, _details]) =>
_emp.map((item) => {
return ( {
...item,
details: _details.find((item1) => {
return item1.id === item.id
})
})
})
)
).subscribe(console.log)
I got the result:
[
{id: 1, name: 'aa', age: 20, details: [{address: 'ee'}] }, // {address: 'ff'} missing
{id: 2, name: 'bb', age: 21, details: [{address: 'gg'}] }, // {address: 'hh'} missing
{id: 3, name: 'cc', age: 22, details: undefined },
{id: 4, name: 'dd', age: 23, details: undefined },
]
In this result second address is missing for id 1 and 2.
Instead of [{address: 'ee'},{address: 'ff'}], I got only first match [{address: 'ee'}] for id 1.
Instead of [{address: 'gg'},{address: 'hh'}], I got only first match [{address: 'gg'}] for id 2.
Please help me to accomplish the desired result
I think you should use filter() instead of find(). The find() operator returns only the first match.
forkJoin([emp, details]).pipe(
map(([_emp, _details]) =>
_emp.map((item) => {
return ({
...item,
// This is the line you have to modify:
details: _details.filter((item1) => item1.id === item.id)
})
})
)
).subscribe(console.log)

Can't access specific data in jsonfile - Flutter

I have this json file :
{
projects: [
{
projectId: 3
projectName: "Complexe hotelier croisette",
workflow: "en cours",
realCalendars: [
{
id: 29,
start: 1630590443000
end: 1648475243000
type: 0
remark: NULL
status: 0
calendarId: NULL
}
],
scheduledCalendars: [
{
id: 30,
start: 1630590443000
end: 1646059643000
type: 0
remark: NULL
status: 0
calendarId: NULL
}
],
lastPlanningModif: 1639320443000
planned: 164,
actual: 142,
remaining: 25,
resourceTaskNumber: 1,
projectTaskNumber: 18,
leaderId: 8,
resourceIds: [8, 7, 6],
dashbordField: 3,
dashbordTendency: 1,
weatherComments: [
{
message: "weather 5",
date: 1645195643000
source: 1
taskId:0
projectId: 3
authorId: 8,
messageId: 31,
messageParentId: 32
},
{
message: "weather 6",
date: 1643813243000
source: 1
taskId: 0
projectId: 3
authorId: 8,
messageId: 33,
messageParentId: 34
},
{
message: "weather 7",
date: 1642776443000
source: 1
taskId: 0
projectId: 3
authorId: 7,
messageId: 35,
messageParentId: 36
},
],
projectComments: [
{
message: "Time 3",
date: 1642776443000
source: 4
taskId: 3789
projectId: 3
authorId: 7,
messageId: 37,
messageParentId: 38
},
{
message: "Time 4",
date: 1639838843000
source: 4
taskId: 3876
projectId: 3
authorId: 8,
messageId: 39,
messageParentId: 40
},
{
message: "Time 5",
date: 1638888443000
source: 2
taskId: 3258
projectId: 3
authorId: 8,
messageId: 41,
messageParentId: 42
},
],
},
{
projectId: 2
projectName: "Festival de la moutarde de Dijon",
workflow: "objectif",
realCalendars: [
{
id: 23,
start: 1682689643000
end: 1696686443000
type: 0
remark: NULL
status: 0
calendarId: NULL
}
],
scheduledCalendars: [
{
id: 24,
start: 1682689643000
end: 1696686443000
type: 0
remark: NULL
status: 0
calendarId: NULL
}
],
lastPlanningModif: 1646059643000
planned: 150,
actual: 0,
remaining: 150,
resourceTaskNumber: 2,
projectTaskNumber: 10,
leaderId: 4,
resourceIds: [4, 6, 7, 8],
dashbordField: 4,
dashbordTendency: 2,
weatherComments: [
{
message: "weather 4",
date: 1674744443000
source: 1
taskId: 0
projectId: 1
authorId: 4,
messageId: 25,
messageParentId: 26
}
],
projectComments: [
],
},
{
projectId: 1
projectName: "Red Is Dead",
workflow: "en cours",
realCalendars: [
{
id: 9,
start: 1642430843000
end: 1669387643000
type: 0
remark: NULL
status: 0
calendarId: NULL
}
],
scheduledCalendars: [
{
id: 10,
start: 1642430843000
end: 1666705643000
type: 0
remark: NULL
status: 0
calendarId: NULL
}
],
lastPlanningModif: 1645109243000
planned: 280,
actual: 58,
remaining: 222,
resourceTaskNumber: 5,
projectTaskNumber: 36,
leaderId: 4,
resourceIds: [4,5,6],
dashbordField: 2,
dashbordTendency: 3,
weatherComments: [
{
message: "weather 1",
date: 1645800443000
source: 1
taskId: 0
projectId: 1
authorId: 4,
messageId: 11,
messageParentId: 12
},
{
message: "weather 2",
date: 1643986043000
source: 1
taskId: 0
projectId: 1
authorId: 4,
messageId: 13,
messageParentId: 14
},
{
message: "weather 3",
date: 1643122043000
source: 1
taskId: 0
projectId: 1
authorId: 4,
messageId: 15,
messageParentId: 16
},
],
projectComments: [
{
message: "Time 1",
date: 1642862843000
source: 4
taskId: 1234
projectId: 1
authorId: 5,
messageId: 17,
messageParentId: 18
},
{
message: "Time 2",
date: 1642258043000
source: 4
taskId: 1235
projectId: 1
authorId: 5,
messageId: 19,
messageParentId: 20
},
{
message: "Task 1",
date: 1641826043000
source: 2
taskId: 1234
projectId: 1
authorId: 5,
messageId: 21,
messageParentId: 22
},
],
}
],
avatars: [
{
resourceId: 8,
idSource: 81,
resourceName: "Alain Martoni",
trigram: "AMO",
imgBase64: ""
},
{
resourceId: 4,
idSource: 41,
resourceName: "Odile Deray",
trigram: "ODE",
imgBase64: ""
},
{
resourceId: 7,
idSource: 71,
resourceName: "Patrick Bialès",
trigram: "PBI",
imgBase64: " "
},
{
resourceId: 5,
idSource: 51,
resourceName: "Serge Karamazov",
trigram: "SKA",
imgBase64: ""
},
{
resourceId: 6,
idSource: 61,
resourceName: "Simon Jérémi",
trigram: "SJE",
imgBase64: ""
}
]
}
Here I try to display specific data from the json (here I want to display what's in "projects")
var resp = response.body;
print("mydata : " + resp['projects'].toString());
Then I tried adding a jsonDecode :
var resp = jsonDecode(response.body);
print("mydata : " + resp['projects'].toString());
Then jsonEncode :
var resp = jsonEncode(response.body);
print("mydata : " + resp['projects'].toString());
Then both :
var resp = jsonDecode(jsonEncode(response.body));
print("mydata : " + resp['projects'].toString());
When I try display only "resp" it works, but it's the access to a specific part (like "projects") of the JSON that doesn't work. The only thing that work is with an int and it display the specific caractere of the index as if the JSON was read as a String.
var resp = jsonDecode(jsonEncode(response.body));
print("mydata : " + resp[0].toString());
//display the first caracter of the JSON
The thing is when I read the response of POST HTTP requests, using jsonEncode then jsonDecode works perfectly, I can then easily access any part of the JSON :
var response = await http.post(
Uri.parse(url),
body: jsonEncode({
"jsonrpc": "2.0",
"id": "10",
"method": "method",
"params": [someParams]
})
);
var resp = jsonDecode(response.body);
print("response body : " + resp['projects'].toString());
//display the "project" part of the JSON response
But all this doesn't work when trying to access specific parts of my first JSON file.
Is there something wrong with my JSON file ?
Thanks for helping.
Update : commas are missing in the json, I corrected it but still the same probleme
I ran your JSON through a JSON formatter / validator and yes, your json was missing some commas and whatnot.
Check out this Gist I created for your decoding - run it through DartPad.Dev and check out.
I made sure the JSON was a proper string before I ran it through the jsonDecode, then I just simply access its values like this:
var decodedJSON = jsonDecode(json);
print(decodedJSON['projects'].length);
print(decodedJSON['projects'][0]['projectName']);
print(decodedJSON['avatars'].length);
print(decodedJSON['avatars'][0]['resourceName']);
I got the values I expected:
3
Complexe hotelier croisette
5
Alain Martoni
I think your issue was just badly formatted JSON coming out of the pipe. Check out the Gist and let me know.

Spring + React fetch data

i have a problem with fetch data from api exposed by spring.
I want to fetch data by:
componentDidMount() {
this.setState({isLoading: true});
fetch('http://localhost:8080/api/tasks/')
.then(response => { return response.json() })
.then(results => this.setState({
tasks: results,
isLoading: false
}));
The spring api which return data:
#CrossOrigin(origins = "http://localhost:3000")
#GetMapping
public List<Task> findTasksByUserId() {
return taskService.findTasksBelongToUser(idProvider.getCurrentUserId());
}
Returned JSON:
[
{
id: 1,
version: 0,
name: "Task1",
description: "description1",
priority: 1,
finished: true,
category: {
id: 1,
version: 0,
name: "Uncategorized",
user: {
id: 1,
version: 0,
login: "admin",
email: "admin#todo.pl",
enabled: true
}
},
user: {
id: 1,
version: 0,
login: "admin",
email: "admin#todo.pl",
enabled: true
},
position: 0
},
{
id: 2,
version: 0,
name: "Task2",
description: "description2",
priority: 4,
finished: true,
category: {
id: 1,
version: 0,
name: "Uncategorized",
user: {
id: 1,
version: 0,
login: "admin",
email: "admin#todo.pl",
enabled: true
}
},
user: {
id: 1,
version: 0,
login: "admin",
email: "admin#todo.pl",
enabled: true
},
position: 1
}]
And i got a error like this:
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
I dont know what is wrong but maybe format of json is not correct, because it's start with the sign '['.
I am a beginner in React so please about some hint and help.
regards
fetch() returns a promise which gets resolved into an HTTP response of course, not the actual JSON. To extract the JSON body content from the response, we use the json() method.
Try adding two headers Content-Type and Accept to be equal to application/json.
fetch('http://localhost:8080/api/tasks/', {
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then(response => { return response.json() })
.then(results => this.setState({
tasks: results,
isLoading: false
}));

angular encode part of $scope to json

I'm working with angular and have most of my api functioning, but I'm having trouble with a put function. My server is hosted by an arduino and can't receive all the data sent by the json stringify.
How to make a JSON obj with only certain $scope data?
This is what I've got so far, with 'chanObj'. The alert returns in some tests "undefined", and on other tests an empty object at the end of the scope.
$scope.setpointClk = function(channel, setpoint) {
var channels = JSON.stringify($scope.channels); //original obj to big
var chanObj = {setPoint : channel.setPoint, name : channel.name
}; //try to create a selected content obj
alert(chanObj);
service.putChannels(channels, function() {
$scope.init();
});
}
channels: [{name: null, canal: "0", status: false, temperature: 19.94, setPoint: 0, permission: false,…},…]
0: {name: null, canal: "0", status: false, temperature: 19.94, setPoint: 0, permission: false,…}
1: {name: null, canal: "1", status: false, temperature: 20.37, setPoint: 5, permission: false,…}
2: {name: null, canal: "2", status: false, temperature: 0, setPoint: 5, permission: false, percentOut: 0}
3: {name: null, canal: "3", status: false, temperature: 0, setPoint: 5, permission: false, percentOut: 0}
4: {name: null, canal: "4", status: false, temperature: 19.94, setPoint: 5, permission: false,…}
5: {name: null, canal: "5", status: false, temperature: 19.87, setPoint: 5, permission: false,…}
6: {name: null, canal: "6", status: false, temperature: 19.98, setPoint: 5, permission: false,…}
7: {name: null, canal: "7", status: false, temperature: 19.96, setPoint: 5, permission: false,…}
8: {name: null, canal: "8", status: false, temperature: -50, setPoint: 5, permission: false,…}
9: {name: null, canal: "9", status: false, temperature: -50, setPoint: 5, permission: false,…}
You should create your chanObj without first calling the JSON.stringify function. Because that would convert your $scope.channels into a string.
E.g. on how to create your chanObj with specific properties from your $scope.channels
$scope.setpointClk = function(channel, setpoint) {
...
var chanObj = {
setPoint: $scope.channels.setPoint,
name: $scope.channels.name
};
...
}
Just create a new object and pass that to the put call, like you have with the chanObj object, pass that to the put.
If you have a lot of properties to maintain, you could do something like this:
var propertiesToCopy = ["setPoint", "name", "foo", "bar"],
cutdownVersion = {};
for(var key in propertiesToCopy) {
cutdownVersion[key] = channels[key];
}
Then pass the cutdownVersion object to the put call.

Show specific attachment using json api for Wordpress

When I go to:
example.com/api/get_tag_posts/?dev=2&slug=ME3022&include=attachments
I see:
{
status: "ok",
count: 1,
pages: 1,
tag: {
id: 17,
slug: "me3022",
title: "ME3022",
description: "",
post_count: 1
},
posts: [
{
id: 181,
attachments: [
{
id: 397,
url: "http://example.com/files/2012/10/WebInstruction_TCH.pdf",
slug: "webinstruction_tch-3",
title: "Traditional Chinese",
description: "",
caption: "Traditional Chinese",
parent: 181,
mime_type: "application/pdf"
},
{
id: 398,
url: "http://example.com/files/2012/10/WebInstruction_SCH.pdf",
slug: "webinstruction_sch-3",
title: "Simplified Chinese",
description: "",
caption: "Simplified Chinese",
parent: 181,
mime_type: "application/pdf"
},
What I want to show is a specific attachment instead of all of the attachments. How can I do that?
To get the a specific attachment &include=attachments,id=51