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 !
Related
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>';
I have a JSON response where i am getting some questions. Now after getting those questions i want to split them into words and match those words with another JSON response and on match i want to highlight those words and make them clickable so i can show a pop up which contains that word's translation which is present in my 2nd response. At the last i want to show both matched and unmatched words together just like it was a question before but with clickable words.
This is what i want
this is my first json
"status": "true",
"message": "message",
"demo": [
{
"qtnNumber": 1,
"qtnItalian": "Il segnale raffigurato preannuncia un tratto di strada in cui è consentita la manovra di retromarcia",
"qtnCategory": "SEGNALEI VERTICALI DI PERICOLO",
"qtnType": true
},
{
"qtnNumber": 2,
"qtnItalian": "Il segnale strada in cui è consentita la manovra di retromarcia",
"qtnCategory": "SEGNALEI VERTICALI DI PERICOLO",
"qtnType": true
},
this is my second json
{
"status": "true",
"message": "Vocabulary",
"vocabulary": [
{
"id": 3406,
"italian": "a condizione ",
"punajbi": "ਹਾਲਾਤ ਕੰਡੀਸ਼ਨ",
"english": "condition",
"number": null,
"punjabiEnglish": "halat",
},
{
"id": 3407,
"italian": "a raso",
"punajbi": "ਪਲੇਨ ਇਸ ਦਾ ਬੁੱਕ ਵਿੱਚ ਪੂਰਾ ਲਫ਼ਜ਼ ਹੇ incrocio a raso => ਇਸ ਦਾ ਮਤਲਬ ਪਲੇਨ ਚੌਕ ਇੱਕੋ ਲੈਵਲ ਤੇ ਬਣਿਆ ਹੋਇਆ ਚੌਕ",
"english": "plane",
"number": "ikO LEVEL DA CHONK",
"punjabiEnglish": null,
},
{
"id": 3408,
"italian": "accesso",
"punajbi": "ਦਾਖਿਲ",
"english": "Entry",
"number": null,
"punjabiEnglish": "Dakhil",
}
now from first json after splitting each question into words i want to match those words with my 2nd json 'italian' field and if matched i want to highlight those words
import 'dart:convert';
const raw_sentences = '''
{
"status": "true",
"message": "message",
"demo": [
{
"qtnNumber": 1,
"qtnItalian": "Il segnale raffigurato preannuncia un tratto di strada in cui è consentita la manovra di retromarcia",
"qtnCategory": "SEGNALEI VERTICALI DI PERICOLO",
"qtnType": true
},
{
"qtnNumber": 2,
"qtnItalian": "Il segnale strada in cui è consentita la manovra di retromarcia",
"qtnCategory": "SEGNALEI VERTICALI DI PERICOLO",
"qtnType": true
}
]
}
''';
const raw_vocabulary = '''
{
"status": "true",
"message": "Vocabulary",
"vocabulary": [
{
"id": 3406,
"italian": "a condizione ",
"punajbi": "ਹਾਲਾਤ ਕੰਡੀਸ਼ਨ",
"english": "condition",
"number": null,
"punjabiEnglish": "halat"
},
{
"id": 3407,
"italian": "a raso",
"punajbi": "ਪਲੇਨ ਇਸ ਦਾ ਬੁੱਕ ਵਿੱਚ ਪੂਰਾ ਲਫ਼ਜ਼ ਹੇ incrocio a raso => ਇਸ ਦਾ ਮਤਲਬ ਪਲੇਨ ਚੌਕ ਇੱਕੋ ਲੈਵਲ ਤੇ ਬਣਿਆ ਹੋਇਆ ਚੌਕ",
"english": "plane",
"number": "ikO LEVEL DA CHONK",
"punjabiEnglish": null
},
{
"id": 3408,
"italian": "accesso",
"punajbi": "ਦਾਖਿਲ",
"english": "Entry",
"number": null,
"punjabiEnglish": "Dakhil"
},
{
"id": 3500,
"italian": "preannuncia"
},
{
"id": 3501,
"italian": "consentita"
}
]
}
''';
void main(List<String> args) {
var sentence = jsonDecode(raw_sentences)['demo'][0]['qtnItalian'] as String;
var vocabulary = jsonDecode(raw_vocabulary)['vocabulary'] as List;
var words = sentence.split(' ');
var matches = vocabulary.map<String>((m) => (m as Map<String, dynamic>)['italian']).toSet().intersection(words.toSet()).toList();
var references = Map.fromEntries(List.generate(matches.length, (i) => MapEntry(matches[i], vocabulary.firstWhere((m) => m['italian'] == matches[i])['id'])));
var new_sentence = <Map<String, dynamic>>[];
var idx = 0;
words.forEach((word) {
if (matches.contains(word)) {
new_sentence.add({'string': word, 'reference': references[word]});
idx += 2;
} else {
if (new_sentence.isEmpty || idx == new_sentence.length) new_sentence.add({});
new_sentence[idx]['string'] = (new_sentence[idx]['string'] ?? '') + ' $word';
}
});
print(sentence);
print(new_sentence);
}
Result:
Il segnale raffigurato preannuncia un tratto di strada in cui è consentita la manovra di retromarcia
[{string: Il segnale raffigurato}, {string: preannuncia, reference: 3500}, {string: un tratto di strada in cui è}, {string: consentita, reference: 3501}, {string: la manovra di retromarcia}]
With the new_sentence list you can create widgets (texts and buttons) to get your goal, that is the easy part and it is your work. Remember, this site is for help, it is not to do your whole work. Good day.
I fetch data from WordPress to react. If data comes in array format I can fetch it, show the content, and map it. But when it comes to JSON Object, I have problems showing the parts I want and also I cannot map it.
my json object simplified = http://myname/wp-json/wp/v2/pages/2
{
"id": 2,
"date": "",
"guid": {
"rendered": ""
},
"content": {
"rendered": "\n<p>Dit is een voorbeeldpagina. Gevestigd in Gotham City, XYZ heeft meer dan 2000 mensen in dienst en doen allemaal fantastische dingen voor de community in Gotham.</p>",
"protected": false
},
"_links": {
"self": [
{
"href": "..."
}
],
"collection": [
{
"href": "..."
}
]
}
}
my useFetch component
export default function useFetch(url) {
const [data, setData] = useState([]);
useEffect(() => {
async function loadData() {
const response = await fetch(url);
if(!response.ok) {
// oups! something went wrong
return;
}
const posts = await response.json();
setData(posts);
}
loadData();
}, [url]);
return data;
}
the component I want to show the data
function Page(props) {
const voorbeeldpagina = useFetch(
"http://myname/wp-json/wp/v2/pages/2"
);
// const newArray = Object.entries(voorbeeldpagina)
// I have also tried OBject.keys and Object.values
return (
<div>
<h1>Page Component</h1>
<div> {**I want to show `content.rendered` from my json object**} </div>
</div>
)
}
I want to show content.rendered from my json object
can anyone help?
Thanks!
well you are trying to map an object you can use object.keys to map them.
Object.keys(posts).map((key)=>return(
//your code goes here
)
This is My JSON text from any URL http://www.example.com/json.php
Please can any one tell me how do I parse this json and put it in an Array so that it can be modal on customized ListView?
Let me tell you that I am new to Blackberry development previously iOS developer.
I have checked this link, but not able to run it .
If any one have any complete solution(example or usage) please help me.
I downloaded the sample of JSON from developer.blackberry.com, but not able to run .
I also posted that question at this link
{
"status": "success",
"result": [
{
"offer_id": "456",
"member_id": "648",
"offer_type": "printable",
"cat_name": "Health & Wellbeing",
"price": "50",
"discount": "20% Off.",
"title": "20% Off",
"quantity": "200",
"details": "Enjoy 20% Off any Service.",
"coupon_code": "45600010106",
"company_logo": "http://beta/files/offers/logos/",
"offer_image": "http://beta/files/offers/images/f4d118737e_image_456.jpg",
"bc_image": "http://beta/files/offers/qrcodes/qrcouponid_45600010106.png",
"company_address1": "Oud Metha - Mohammed Saeed Hareb Bldg. Opp. American Hospital",
"company_address2": "Not Available",
"company_city": "Not Available",
"company_phone": "04 357 6738 Mob: 509284567",
"location": "Oud Metha",
"company_name": "Golden House Gents Spa Club",
"merchant_name": "Golden House Gents Spa Club",
"url": "http://google.com",
"date_end": "2013/12/30",
"date_start": "2013/07/25",
"condition": "1. Cannot be Combined with any other offer.\r\n2. Advance booking required.\r\n3. This Voucher must be Mentioned during time of Booking.\r\n4. Not Valid on Thurs & Sat.\r\n5. Expires 31st December 2013.",
"rating": "0",
"latitude": "25.2374",
"longitude": "55.3117"
}
]
}
It's all explained in the documentation of JsonDataAccess. You'll have to do something like this:
// Create a data model with sorting keys for title
GroupDataModel *model =
new GroupDataModel(QStringList() << "title");
// Load the JSON data
JsonDataAccess jda;
QVariant list = jda.load("yourfile.json")["result"].toVariantList();
// Add the data to the model
model->insertList(list.value<QVariantList>());
// Add your model to a ListView
listView->setDataModel(model);
This is the QML way of doing it, you don't have to touch any C++ code.
First you need to create a listview in a QML file.
ListView {
id: listData
dataModel: ArrayDataModel {
id: theDataModel
}
....
}
Now you will want to populate your listview with the data from a json file. Since you are making a call to the server, you will want to send a request.
function sendRequest() {
console.log("DEBUG: sending request");
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
// Need to wait for the DONE state or you'll get errors
if (request.readyState === XMLHttpRequest.DONE) {
if (request.status === 200) {
// if response is JSON you can parse it
var response = JSON.parse(request.responseText);
theDataModel.append({
"offer_id": response.result.offer_id,
"member_id": response.result.member_id,
"offer_type": response.result.offer_type
});
}
} else {
// Error
console.log("DEBUG: Status: " + request.status + ", Status Text: " + request.statusText);
}
}
// POST/GET request
request.open("GET", "http://www.example.com/json.php", true);
request.setRequestHeader("Accept", "application/json");
request.send();
}
And to display the values, you can use StandardListItem:
StandardListItem {
title: ListItemData.offer_id
description: ListItemData.offer_type
status: ListItemData.member_id
}
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);
}
}