Create and retrieve "multi-level" data in JSON - json

For a course exercise, a friend of mine has to dynamize a website with a JSON. The problem occurs when I try to search for data on several levels. Basically, Elles wants to allow to choose ornaments. There are handles or screw covers available, and there are two of each. The problem is that I can't properly structure my JSON to make this possible, or to retrieve the data.
{
"id" : 4,
"nom":"Cercueil Les Borgia",
"description": "Ce cercueil demi-tombeau en chêne massif , vous propose de le personnaliser en s'inspirant des jardins les plus fleuris mais aussi les plus dangereux",
"prix" : 800 ,
"image" :"medias/chenemassif1.png" ,
"motifs":
[
{
"natureMo":"Fleur",
"prixMo": "30",
"disponibiliteMo":true
},
{
"natureMo":"Vichy",
"prixMo": "30",
"disponibiliteMo":true
}
],
"couleurs":
[
{
"nomCo": "Vert clair",
"code": "#93C97F"
},
{
"nomCo": "Violet",
"code": "#64527A"
}
],
"ornements": [
{
"types": [
{
"Poignées": [
{
"style": "Romaine",
"prixOr": 22,
"disponibiliteOr":true
},
{
"style":"Flamme Eco",
"prixOr":22,
"disponibiliteOr":true
}
]
},
{
"Cache-vis" : [
{
"style":"Roseau",
"prixOr":18,
"disponibiliteOr":true
},
{
"style":"Hexagonale",
"prixOr":18,
"disponibiliteOr":false
}
]
}
]
}
]
}
I've tried to put both ornament types in one type category, and use it, but that doesn't work either when I try to retrieve the data.
res += '<h3>Ornements</h3>';
for(l=0; l<doc[i].ornements.length; l++){
var ornementsNaCer = doc[i].ornements[l].types;
res += '<h4>'+ ornementsNaCer +'</h4>';

Related

object Angular to array

How can I get only the data array from the observable response ?, I need to get the values ​​of cat_id,cat_name,cat_description but not the sql_types array
{
"code": 0,
"message": "",
"data": [
{
"cat_name": "Topografía",
"cat_description": "Servicios de topografía en general",
"cat_id": 1
},
{
"cat_name": "Estructuras hormigón",
"cat_description": "subcontratas de estructuras de hormigón ",
"cat_id": 3
}
],
"sqlTypes": {
"cat_name": 12,
"cat_description": 12,
"cat_id": 4
}
}
You can pipe your observable and map it to the object you want.
Only your data will be availible in the example below
Observable.pipe(map(resp => resp.data)).subscribe(data=> //do something)

Flutter l10n - Dynamic key

I am actually coding a multi-language app and I have a problem to get my resources on different languages. My app is currently working on one language with a json file.
For example I got :
{
"Resorts" : [
{
"name": "Walt Disney World Resort",
"slug": "waltdisneyworldresort",
"description": "Explorez des terres d'enchantement infini, où vos fantasmes deviennent réalité !"
},
{
"name": "Disneyland Resort",
"slug": "disneylandresort",
"description": "Regardez les rêves devenir réalité dans l'endroit le plus heureux de la planète !"
},
]
}
I started using l10n and I have my files app_en.arb:
{
"##locale": "en",
"resortDesc": "English description",
"#resortDesc": {
"description": "Description of the resort that will be displayed on the cards in the Resort Selection screen",
}
}
and app_fr.arb:
{
"##locale": "fr",
"resortDesc": "Description en Français",
"#resortName": {
"description": "Description du resort qui sera affiché sur la page 'Resort Selection'",
}
}
But this means that I need to call my texts with something like:
AppLocalizations.of(context)!.resortDesc
While I was calling my texts from my json as:
Future<void> readJsonDatas() async {
final String res = await rootBundle.loadString("assets/datas.json");
final data = await jsonDecode(res);
setState(() {
datas = data;
});
await datas;
for(var data in datas['Resorts']) {
parks.add(
Resort(name: data['name'], imagePath: data['image'], slug: data['slug'], bgImagePath: data['bg_image'], description: data['description'], parks: data['parks'] ?? [], lat: data['latitude'], long: data['longitude'])
);
}
currentResort = parks[0]; // Default park
}
Do you have any idea what I could do in app_en.arb and app_fr.arb to get my datas as:
AppLocalizations.of(context)!.datas['slug'].description
Or how I should do it ?
Many thanks for your tips,
Have a great day !

How I can utilise json with scala?

I utilise IntelliJ and not sbt.
I have a task where I need to create a post. I need to enter this information:
{
"packages": [
{
"uid": "...",
"x": 21.27,
"y": 23.36
},
{
"uid": "...",
"x": -16.01,
"y": -12.82
},
{
"uid": "...",
"x": 19.38,
"y": 1.77
}
],
"mailmen": [
{
"uid": "...",
"x": 14.68,
"y": 9.69
},
{
"uid": "...",
"x": 0.08,
"y": -3.34
}
]
}
And I've done the programm and I have classes:
class livreur(var uid:String,var xMaison:Double,var yMaison:Double,var x:Double,var y:Double,var distance:Double=0.0){
def afficherL : Unit ={
println("Uid "+uid)
println("Distance: "+distance)
}
}
class packages(var uid:String,var x:Double,var y:Double,var uidLivre:String=""){
def afficherP : Unit ={
println("Uid "+uid)
}
}
Functions which I utilise to create objects:
def saisirLivreur():livreur={
val uidLiv=readLine("Uid: ").toString
val xMaison=readLine("X: ").toDouble
val yMaison=readLine("Y: ").toDouble
return new livreur(uidLiv,xMaison,yMaison,xMaison,yMaison)
}
def saisirPackage():packages={
val uidPack=readLine("Uid: ").toString
val xPack=readLine("X: ").toDouble
val yPack=readLine("Y: ").toDouble
return new packages(uidPack,xPack,yPack)
}
**My questions are:
how I can connect my class with input information and how I can output the information in format which I need in the end if I have 2 ArraysBuffers, 1st with all couriers (livrMaison) and 2nd with all delivered packages (packagesLivré). :
[
{
"uid": "uid-du-livreur",
"tour": [ //liste des colis à distribuer, dans l'ordre
"uid-du-premier-colis-de-la-tournee-de-ce-livreur"
],
"length": 28.670242284303 //longueur totale du parcours
},
{
"uid": "uid-du-livreur",
"tour": [ //liste des colis à distribuer, dans l'ordre
"uid-du-premier-colis-de-la-tournee-de-ce-livreur",
"uid-du-second-colis-de-la-tournee-de-ce-livreur"
],
"length": 106.54693343859 //longueur totale du parcours
}
]
**
Please help me.
Thanks,-N
Classes in scala should be Upper case Livreur instead of livreur
to parse and produce json use one of existing libraries. I propose upickle (http://www.lihaoyi.com/upickle/) (add ibraryDependencies += "com.lihaoyi" %% "upickle" % "0.9.5" to build.sbt)

How to get each value from specific key from a JSON in Ruby

I have the following JSON:
{"connection": {
"informations": {},
"id_user": 6909,
"subscriptions": [
{
"id_source": 69825,
"documents": [
{
"id_subscription": 5265,
"thumb_url": "https://test-sandbox.biapi.pro/2.0/users/me/documents/1244/thumbnail/test%40hotmail.fr_305146953_thumbnail.png",
"name": "Facture de 44.96€ du 2019-11-18",
"id_thumbnail": 40343,
"url": "https://test-sandbox.biapi.pro/2.0/users/me/documents/1244/file/test%40hotmail.fr_305146953.pdf",
"untaxed_amount": null
},
{
"id_subscription": 5265,
"thumb_url": "https://mooncard23-sandbox.biapi.pro/2.0/users/me/documents/1245/thumbnail/test%40hotmail.fr_290804394_thumbnail.png",
"name": "Facture de 13.98€ du 2019-05-29",
"url": "https://mooncard23-sandbox.biapi.pro/2.0/users/me/documents/1245/file/test%40hotmail.fr_290804394.pdf",
"untaxed_amount": null
}
]
}
]
}
}
I try to get all the values like "https://test-sandbox.biapi.pro/2.0/users/me/documents/1246/file/test%40hotmail.fr_274475652.pdf"
My JSON is rendered like this in my controller:
render json: params.to_json
When I try to get all the values URL in this way:
params.dig('connection','subscriptions').each_with_object([]) { |x, arr| x['documents'].each { |d| arr << d['url'] } }
I have the error undefined method each_with_object for nil:NilClass.
Here is the simple as simple solution that is easy to understand.
You can try this:
JSON.parse(params)["invoice"]["connection"]["subscriptions"].map { |subscription|
subscription["documents"].map{ |document| document["url"] }
}
[[
"https://mooncard23-sandbox.biapi.pro/2.0/users/me/documents/1244/file/test%40hotmail.fr_305146953.pdf",
"https://mooncard23-sandbox.biapi.pro/2.0/users/me/documents/1245/file/test%40hotmail.fr_290804394.pdf",
"https://mooncard23-sandbox.biapi.pro/2.0/users/me/documents/1246/file/test%40hotmail.fr_274475652.pdf"
]]

Limitation in the number of posts to fetch with Blogger API (error 400)

I am trying to fetch all the post from a blog using the Blogger API. The maximum number of posts to fetch seems to be limited to 20 for some unknown reasons.
If I try this URL:
https://www.googleapis.com/blogger/v3/blogs/3089072491354463482/posts?maxResults=20&fields=items(title)&key=AIzaSyAJO5J-pRCaGOIeRLIJfvAPwxpMLKvwebU
I get the following response (listing the last 20 post titles as expected):
{
"items": [
{
"title": "El Caballero"
},
{
"title": "Une traversée de frontière… étonnante!"
},
{
"title": "Hasta luego querida Argentina!"
},
{
"title": "Dernier jour en Argentine"
},
{
"title": "Humahuaca"
},
{
"title": "Purmamarca"
},
{
"title": "Tilcara"
},
{
"title": "Premières grèves"
},
{
"title": "Le Nord Argentin: Salta"
},
{
"title": "Ca en fait de l'eau tout ça..."
},
{
"title": "Un peu de pluie au Brésil"
},
{
"title": "Iguazu"
},
{
"title": "San José"
},
{
"title": "Adieu à Buenos Aires"
},
{
"title": "Traversons en Uruguay"
},
{
"title": "Retour à Buenos Aires"
},
{
"title": "Fin de l'aventure Patagonienne"
},
{
"title": "Les fameuses tours nous surprennent"
},
{
"title": "Un peu de pluie pour se changer les idées"
},
{
"title": "Valle Francés"
}
]
}
However, if I increase the maxResults parameters,
https://www.googleapis.com/blogger/v3/blogs/3089072491354463482/posts?maxResults=21&fields=items(title)&key=AIzaSyAJO5J-pRCaGOIeRLIJfvAPwxpMLKvwebU
I get the following error:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "invalid",
"message": "Invalid Value"
}
],
"code": 400,
"message": "Invalid Value"
}
}
How could I increase the limitation in the maximum number of post that I can fetch?
Thanks,
Nicolas
I think that the API is limited to only pull 20 results as a maximum.
So in order to fetch more than 20 results you have to use the pageToken parameter as specified in Bloggers's reference API.
Your first request should include the nextPageToken so you will have it in the response. Than use this token to retrieve the next page and so on.
Your first request must be like this :
https://www.googleapis.com/blogger/v3/blogs/3089072491354463482/posts?maxResults=20&fields=items%28title%29%2CnextPageToken&key=AIzaSyAJO5J-pRCaGOIeRLIJfvAPwxpMLKvwebU
Here is the expected result :
{
"nextPageToken": "CgkIChignPaz5ycQ-rn0pIfipe8q",
"items": [
{
"title": "El Caballero"
},
{
"title": "Une traversée de frontière… étonnante!"
},
{
"title": "Hasta luego querida Argentina!"
},
{
"title": "Dernier jour en Argentine"
},
{
"title": "Humahuaca"
},
{
"title": "Purmamarca"
},
{
"title": "Tilcara"
},
{
"title": "Premières grèves"
},
{
"title": "Le Nord Argentin: Salta"
},
{
"title": "Ca en fait de l'eau tout ça..."
}
]
}
Now all you have to do is to pick the "nextPageToken": "CgkIChignPaz5ycQ-rn0pIfipe8q" in the result and include it in you next request like this :
https://www.googleapis.com/blogger/v3/blogs/3089072491354463482/posts?%20maxResults=20&pageToken=CgkIChignPaz5ycQ-rn0pIfipe8q&fields=items%28title%29%2CnextPageToken&key=AIzaSyAJO5J-pRCaGOIeRLIJfvAPwxpMLKvwebU
The result should show the next 20 posts in addition to a new ``nextPageToken` to use in the next request.
I implemented what was suggested by Walid Laribi for a travel blog page that retrieve the location of all the posts from the blog and draw the path taken during the travel (blog).
To fetch the location of all the posts, I have first a script that retrieves the first 10 posts and gives me the nextPageToken:
<script src="https://www.googleapis.com/blogger/v3/blogs/3089072491354463482/posts?fields=nextPageToken,items(title,location(name,lat,lng),url,published)&key=AIzaSyAJO5J-pRCaGOIeRLIJfvAPwxpMLKvwebU&callback=handleResponse">
In the callback of the previous script, we can get the location of each post as well as creating and executing the script to fetch the next posts:
// Get latitude/longitude from Blogger
function handleResponse(response) {
for(i=0; i< response.items.length; i++){
if(response.items[i].location != undefined){
Lat.push(response.items[i].location.lat);
Lng.push(response.items[i].location.lng);
// etc.
}
}
if(response.nextPageToken != undefined){
var srctxt = 'https://www.googleapis.com/blogger/v3/blogs/3089072491354463482/posts?fields=nextPageToken,items(title,location(name,lat,lng),url,published)&key=AIzaSyAJO5J-pRCaGOIeRLIJfvAPwxpMLKvwebU&callback=handleResponse&pageToken=' + response.nextPageToken;
// Execute the new script
var head = document.getElementsByTagName('head')[0];
var scriptElement = document.createElement('script');
scriptElement.setAttribute('type', 'text/javascript');
scriptElement.setAttribute('src', srctxt);
head.appendChild(scriptElement);
head.removeChild(scriptElement);
}
}