bring an https request into an object - list

I'm new to flutter and even coding itself. I have a bit experience in Java and C# so I know datatypes and functions, etc.
My problem: I'm not realy firm in lists and maps right now but I have to send a https request and I will receive a list that contains other lists:
example:
[
[
"60",
"49.142000",
"9.362000",
8,
"Obersulmer Kachelofenbau",
"Am Seebach 6",
"74182",
"Obersulm-Willsbach",
"www.obersulmer-kachelofenbau.de",
"",
"07134 - 5 10 36 ",
"info#obersulmer-kachelofenbau.de",
"1557919527",
"DE"
],
[
"48",
"48.917000",
"9.425000",
26,
"K\u00f6gel Schornsteine GmbH",
"Donaustra\u00dfe 17 - 19",
"71522",
"Backnang",
"www.koegel-schornsteine.de",
"",
"07191 95255-40",
"info#koegel-schornsteine.de",
"1557989245",
"DE"
],
]
I created a class to store these data:
class Store {
final String id;
final double lat;
final double long;
final String name;
final String street;
final String zip;
final String city;
final String web;
final String phone;
final String mail;
final String countryCode;
Store(this.id, this.lat, this.long, this.name, this.street, this.zip,
this.city, this.web, this.phone, this.mail, this.countryCode);
}
I don´t need all data of the incoming lists. Only index 0,1,2,4,5,6,7,8,10,11,13 are needed
When I look at the cookbook (https://flutter.dev/docs/cookbook/networking/fetch-data)
it tells me to create the album class (in my case the store class) but it works with a json and I don´t get a json. Maybe I missunderstand the cookbook but in general lists and maps in flutter is not my passion.
Hopefully I provided all infomrations you need in a clear way. If not please ask me.
My main issue is how to get the data I receive into the store class?? I appriciate any help from you.

It's better to use json format for your network api.
If you could not use json, you can use below code. Please make sure your api result format is exactly like above, i mean your requested index should be ready.
void main() async {
List<List> apiResults = [
[
"60",
"49.142000",
"9.362000",
8,
"Obersulmer Kachelofenbau",
"Am Seebach 6",
"74182",
"Obersulm-Willsbach",
"www.obersulmer-kachelofenbau.de",
"",
"07134 - 5 10 36 ",
"info#obersulmer-kachelofenbau.de",
"1557919527",
"DE"
],
[
"48",
"48.917000",
"9.425000",
26,
"K\u00f6gel Schornsteine GmbH",
"Donaustra\u00dfe 17 - 19",
"71522",
"Backnang",
"www.koegel-schornsteine.de",
"",
"07191 95255-40",
"info#koegel-schornsteine.de",
"1557989245",
"DE"
],
];
List<Store> stores = [];
for (var item in apiResults) {
stores.add(Store(
id: item[0],
lat: double.parse(item[1]),
long: double.parse(item[2]),
name: item[4],
street: item[5],
zip: item[6],
city: item[7],
web: item[8],
phone: item[10],
mail: item[11],
countryCode: item[13],
));
}
print(stores);
}
class Store {
final String? id;
final double? lat;
final double? long;
final String? name;
final String? street;
final String? zip;
final String? city;
final String? web;
final String? phone;
final String? mail;
final String? countryCode;
Store(
{this.id,
this.lat,
this.long,
this.name,
this.street,
this.zip,
this.city,
this.web,
this.phone,
this.mail,
this.countryCode});
}

The response from your API can still be parsed as JSON with jsonDecode from the package dart:convert. But the example response you provided contains a trailing comma after the last array, which isn't valid JSON. Therefore, a regular expression can be used to replace the ,] with only ]. This effectively removes the leading commas everywhere, making it valid JSON.
jsonDecode will return your data in a list with lists inside, which can be used to create your objects.
import 'dart:convert';
parse() {
String response = '''[
[
"60",
"49.142000",
"9.362000",
8,
"Obersulmer Kachelofenbau",
"Am Seebach 6",
"74182",
"Obersulm-Willsbach",
"www.obersulmer-kachelofenbau.de",
"",
"07134 - 5 10 36 ",
"info#obersulmer-kachelofenbau.de",
"1557919527",
"DE",
],
[
"48",
"48.917000",
"9.425000",
26,
"K\u00f6gel Schornsteine GmbH",
"Donaustra\u00dfe 17 - 19",
"71522",
"Backnang",
"www.koegel-schornsteine.de",
"",
"07191 95255-40",
"info#koegel-schornsteine.de",
"1557989245",
"DE",
],
]''';
response = response.replaceAll(new RegExp(r',( +|\n)( +)]'), ']');
return jsonDecode(response);
}
void main(List<String> arguments) {
var json = parse();
print(json[0]);
print(json[1]);
}

Related

How to read Json string starting with square brackets in it? [duplicate]

This question already has an answer here:
How to use boost::property_tree to parse JSON with array root
(1 answer)
Closed 2 years ago.
I am using c++ code to read json string to retrieve value based on specific key names. Example of my json response from web API is in array format like below.
[
{
"username": "123456",
"useraddress": "abc",
"data": [
{
"schedule": true,
"task": "abc",
"risk": "1",
}
],
"date": "0000-00-00"
}
]
Like the above format is the actual response. I have to retrieve date value using key "date".
My code snippet:
{
std::stringstream jsonString;
boost::property_tree::ptree pt;
jsonString << ws2s(Info).c_str();
boost::property_tree::read_json(jsonString, pt);
std::string date = pt.get<std::string>("date");
}
'Info' in above snippet is wsstring containing json response data.
I can able to retrieve "date" if [] square brackets are removed manually. Since it is array format, if I pass without removing brackets, read_json throws error.
Can somebody help this out?
Yeah. Boost Property Tree is a property tree library, not JSON.
You're in luck though, Boost has a JSON library now https://www.boost.org/doc/libs/1_75_0/libs/json/doc/html/index.html
Note: your input isn't valid JSON either, because JSON doesn't strictly allow trailing commas. You can enable them with an option in Boost JSON though:
Live On Compiler Explorer
#include <boost/json.hpp>
#include <iostream>
int main() {
std::string input = R"(
[
{
"username": "123456",
"useraddress": "abc",
"data": [
{
"schedule": true,
"task": "abc",
"risk": "1",
}
],
"date": "0000-00-00"
}
])";
boost::json::parse_options options;
options.allow_trailing_commas = true;
auto json = boost::json::parse(input, {}, options);
for (auto& el : json.as_array()) {
std::cout << el.at("date") << "\n";
}
}
Prints
"0000-00-00"

Fetching api with nlohmann/json

I want to use api with c++ and when I searched I found nlohmann/json library it looks really popular but no one talks about how to get the array that fetch function provides . How can I get the information from the api as variables in my cpp file
Didn’t quite understand your description, I assume you mean you want to get the JSON array? You can try this:
std::string ss= R"(
{
"test-data":
[
{
"name": "tom",
"age": 11
},
{
"name": "jane",
"age": 12
}
]
}
)";
json myjson = json::parse(ss);
auto &students = myjson["test-data"];
for(auto &student : students) {
cout << "name=" << student["name"].get<std::string>() << endl;
}

Rails, Highchart maps - adding custom data

I need some basic assistance with a Highmap (via Highcharts) I am trying to put in my Rails 4 app. I suspect I have some fundamental misunderstanding of it but can't find any clear guidance.
See a simple fiddle taken from the documentation, here
http://jsfiddle.net/SimonWalsh/zpdc1btu/
What I ultimately need to do is provide membership numbers for each country so that it will be displayed much the same as the population density is in this map.
I know I need to provide my data and the means to join it to the map data in
series : [{
data : data,
mapData: Highcharts.maps['custom/world'],
joinBy: ['iso-a2', 'code'],
name: 'Population density',
states: {
hover: {
color: '#BADA55'
}
}
}]
In this example, I am guessing that the data is being pulled from an external source and that the map data is the 'iso-a2' part of the array.
If this is the case, then why can't I supply this with my data....as an example see the added array with my data.....(just one example given for Denmark)
var mydata = [
{
"iso-a2": "dk",
"value": 30
},
]
and then do
series : [{
data : mydata,
mapData: Highcharts.maps['custom/world'],
joinBy: ['iso-a2', 'value'],
name: 'Population density',
states: {
hover: {
color: '#BADA55'
}
}
}]
This does not work.....any guidance at all (other than simply pointing me to docs would be greatly appreciated)
The joinBy specifies on which value you map a country with your data. With
joinBy: ['iso-a2', 'code']
you say that the 'iso-a2' value of the mapData should be equal to the 'code' value of your data. Therefore, your data must have this format:
var mydata = [
{
"code": "dk",
"value": 30
},
/* ... */
]

How to search comma separated data in mongodb

I have movie database with different fields. the Genre field contains a comma separated string like :
{genre: 'Action, Adventure, Sci-Fi'}
I know I can use regular expression to find the matches. I also tried:
{'genre': {'$in': genre}}
the problem is the running time. it take lot of time to return a query result. the database has about 300K documents and I have done normal indexing over 'genre' field.
Would say use Map-Reduce to create a separate collection that stores the genre as an array with values coming from the split comma separated string, which you can then run the Map-Reduce job and administer queries on the output collection.
For example, I've created some sample documents to the foo collection:
db.foo.insert([
{genre: 'Action, Adventure, Sci-Fi'},
{genre: 'Thriller, Romantic'},
{genre: 'Comedy, Action'}
])
The following map/reduce operation will then produce the collection from which you can apply performant queries:
map = function() {
var array = this.genre.split(/\s*,\s*/);
emit(this._id, array);
}
reduce = function(key, values) {
return values;
}
result = db.runCommand({
"mapreduce" : "foo",
"map" : map,
"reduce" : reduce,
"out" : "foo_result"
});
Querying would be straightforward, leveraging the queries with an multi-key index on the value field:
db.foo_result.createIndex({"value": 1});
var genre = ['Action', 'Adventure'];
db.foo_result.find({'value': {'$in': genre}})
Output:
/* 0 */
{
"_id" : ObjectId("55842af93cab061ff5c618ce"),
"value" : [
"Action",
"Adventure",
"Sci-Fi"
]
}
/* 1 */
{
"_id" : ObjectId("55842af93cab061ff5c618d0"),
"value" : [
"Comedy",
"Action"
]
}
Well you cannot really do this efficiently so I'm glad you used the tag "performance" on your question.
If you want to do this with the "comma separated" data in a string in place you need to do this:
Either with a regex in general if it suits:
db.collection.find({ "genre": { "$regex": "Sci-Fi" } })
But not really efficient.
Or by JavaScript evaluation via $where:
db.collection.find(function() {
return (
this.genre.split(",")
.map(function(el) {
return el.replace(/^\s+/,"")
})
.indexOf("Sci-Fi") != -1;
)
})
Not really efficient and probably equal to above.
Or better yet and something that can use an index, the separate to an array and use a basic query:
{
"genre": [ "Action", "Adventure", "Sci-Fi" ]
}
With an index:
db.collection.ensureIndex({ "genre": 1 })
Then query:
db.collection.find({ "genre": "Sci-Fi" })
Which is when you do it that way it's that simple. And really efficient.
You make the choice.

Lists AS value of a Map in Dart

I want to create a map of members, but every membres have 3 propreties : first name, last name, and username. How can I create like a list of liste, but with a map.
So I want to have something like :
var membres= {['lastname': 'Bonneau',
'firstname': 'Pierre',
'username': 'mariobross'],
['lastname': 'Hamel',
'firstname': 'Alex',
'username': 'Queenlatifa'],
};
As you know, this code doesn't work. But it explain pretty well what I am trying to do.
I think you are confusing the two constructs here.
Read this introduction to the language: http://www.dartlang.org/docs/dart-up-and-running/ch02.html#lists
A list is a list of elements which can be denoted with the shorthand [...] syntax:
var list = [1, 2, "foo", 3, new Date.now(), 4];
Whereas a map can be denoted with the curly brace shorthand syntax:
var gifts = { // A map literal
// Keys Values
'first' : 'partridge',
'second' : 'turtledoves',
'fifth' : 'golden rings'
};
So, let's modify your code to work:
var members = [
{
'lastname': 'Bonneau',
'firstname': 'Pierre',
'username': 'mariobross'
},
{
'lastname': 'Hamel',
'firstname': 'Alex',
'username': 'Queenlatifa'
}
];
You can, for example, print the information like this:
members.forEach((e) {
print(e['firstname']);
});
If I understand your intent correctly, you want to have a list of maps. What you have is correct except you confused [ and {. The following works:
var membres = [
{'lastname': 'Bonneau',
'firstname': 'Pierre',
'username': 'mariobross'},
{'lastname': 'Hamel',
'firstname': 'Alex',
'username': 'Queenlatifa'}
];
As an example, to get a list of all usernames:
print(membres.map((v) => v['username']));
If you don't really need a Map, what about using a class to improve the structure of your code :
class Member {
String firstname;
String lastname;
String username;
Member(this.firstname, this.lastname, this.username);
}
main() {
final members = new List<Member>();
members.add(new Member('Pierre', 'Bonneau', 'mariobross'));
members.add(new Member('Alex', 'Hamel', 'Queenlatifa'));
// use members
}
You mean like this?
// FirstName => LastName => Value
var lookup = new Map<String, Map<String, String>>();
// get / set values like this
void setValue(String firstName, String lastName, String value) {
if (!lookUp.containsKey(firstName))
lookUp[firstName] = new Map<String, String>();
lookUp[firstName][lastName] = value;
}
String getValue(String firstName, String lastName) {
if (!lookUp.containsKey(firstName)) return "";
return lookUp[firstName][lastName];
}
First of all you need to create a map with value as list. Dont forget to initialize it
then if you want to fill it you first need to use built in function like putIfAbsent as in dart to add first object in list and then use update to add items in list. therefore you will need two arrays. First to put elements and then to add elements in list with same key. Also you can use try catch to identify if the key is present or not to do that in one loop
for (var item in days) {
var date_time = DateTime.parse(item["date"] + " 00:00:00");
_events[date_time] = _events.putIfAbsent(
date_time,
() => [
{
"title": item["title"],
"date": item["date"],
"time": reUse.get_time_am_pm_format(item["time"]),
"feature": item["feature"],
}
]);
}
for (var item in days) {
var date_time = DateTime.parse(item["date"] + " 00:00:00");
_events[date_time] = _events.update(date_time, (value) {
value.add({
"title": item["title"],
"date": item["date"],
"time": reUse.get_time_am_pm_format(item["time"]),
"feature": item["feature"],
});
return value;
});
}