Dart Convert HTML to JSON - flutter

The official Turkey's Dictionary has some kind of json request system but the response it gave is HTML, not JSON.
Example:
https://sozluk.gov.tr/gts?ara=kalem
I'm trying to convert this HTML to JSON but couldn't make it. When I use html plugin on Flutter it gives me some kind of #document every time.
var sozlukurl = await http.Client()
.get(Uri.parse('https://sozluk.gov.tr/gts?ara=$ceviri'));
print(sozlukurl);
var sozlukapibody = parse(sozlukurl.body);
print(sozlukapibody);
var decoded = json.decode(sozlukapibody.toString());
var sozlukbilgi = jsonDecode(utf8.decode(decoded.bodyBytes)) as Map;
var sozlukanlam = sozlukbilgi['anlamlarListe'][0]['anlam'];
print(sozlukanlam);
Output from sozlukurl:
I/flutter ( 5350): Instance of 'Response'
Output from sozlukapibody:
I/flutter ( 5350): #document
Final Error:
FormatException (FormatException: Unexpected character (at character 1)
#document
^
)
How can i solve this problem?

It returns a json with an array encapsulating it. For your particular example jsonDecode should work fine, just take index 0 of the array to access the json.
var res = await http.Client()
.get(Uri.parse('https://sozluk.gov.tr/gts?ara=kalem'));
var body = res.body;
var decoded = jsonDecode(body);
var json = decoded[0];
var sozlukanlam = json["anlamlarListe"][0]["anlam"];
print(sozlukanlam);
I tried it on DartPad and not on an actual app however.

Related

Flutter/Dart convert a string formated as an object into a array

I am attempting to convert a string that is formatted as an object but with no luck, the data is originally formatted as a _CompactLinkedHashSet<String> so i tried to convert it to a json thinking that an array will be the output, below is my code.
var items = dataColumn[index]['items'];
final item = json.decode(json.encode(items.toString()));
When i print(items.runtimeType) the items is equals to _CompactLinkedHashSet<String>
but manage to convert it to a string using json encode and decode but the output is not an array its a string formatted as below
{'Word-1', 'Word-2', 'Word-3'}
I would like to convert it to an array so i can display it inside a ListView.builder like below
['Word-1', 'Word-2', 'Word-3']
You can change like below.
void main() {
var item = {'Word-1', 'Word-2', 'Word-3'};
print(item.runtimeType);
print(item);
// var itemList = item.map((item) => item).toList();
var itemList = List.from(item);
print(itemList.runtimeType);
print(itemList);
}

How to use Dart's Uri to parse links containing #

I want to use dart's uri to parse the following url, the value in the parameter contains a ”#“
String url = 'scheme://a.b.c/d?p={"url": "https://test.test.com/#/a/b"}';
Uri uri = Uri.parse(url);
var map = uri.queryParameters;
print(map);
I want to get the value of parameter p through uri analysis
The result of the above code is as follows:
{p: {"url": "https://test.test.com/}
The desired result is as follows:
{p: {"url": "https://test.test.com/#/a/b}
Thanks!!!
You can try this. First, you replace # with a unique value. After parsing then again replace the hashtag.
String url = 'scheme://a.b.c/d?p={"url": "https://test.test.com/#/a/b"}';
Uri uri = Uri.parse(url.replaceAll("#","hashtag"));
var map = uri.queryParameters;
print(map.toString().replaceAll("hashtag","#"));
output: {p: {"url": "https://test.test.com/#/a/b"}}
The hash # must be replaced with its encoded value %23:
String url = 'scheme://a.b.c/d?p={"url": "https://test.test.com/%23/a/b"}';
The URL you supplied should have had characters with special meanings escaped/encoded in the first place. Uri.parse probably is parsing it correctly; you just gave it malformed input for what you intended.
What you should do instead is to encode the argument for your query string first:
String queryArgument = '{"url": "https://test.test.com/#/a/b"}';
String encodedArgument = Uri.encodeQueryComponent(queryArgument);
String url = 'scheme://a.b.c/d?p=$encodedArgument';
Uri uri = Uri.parse(url);
var map = uri.queryParameters;
print(map); // Prints: {p: {"url": "https://test.test.com/#/a/b"}}

Why fromJson() function of Protobuf not working in Dart

I have an issue with the fromJson() function.
I try to build my protobuf with the data received from Firestore and the fromJson() seems to not be able to parse it.
Facing this issue, I decide to do a test by creating a new empty Protobuf manually, export it as a JSON and create a new protobuf with the json. I got some weird issues:
MyProtobuf my_protobuf = MyProtobuf();
my_protobuf.id = "ABC";
...
// Exporting using writeToJson()
String json1 = my_protobuf.writeToJson(); // All my keys are numbers.. why?
// Exporting using a Map
Map<String, dynamic> json2_map = info_to_write.toProto3Json();
String json2 = JsonEncoder().convert(json2_map); // Seems to be a normal JSON
// Build a protobuf from JSON
MyProtobuf new_protobuf1 = MyProtobuf.fromJson(json1); // Exception thrown
MyProtobuf new_protobuf2 = MyProtobuf.fromJson(json2); // Exception thrown
Is this a bug of Im not using this good function?
This is my proto file:
syntax = "proto3";
package test.v1;
message MyProtobuf {
string id = 1;
string name = 2;
}
To convert a message to json string, you need to use the following code:
MyProtobuf my_protobuf = MyProtobuf();
my_protobuf.id = "ABC";
...
// convert to json object
var obj = my_protobuf.toProto3Json();
// encode to json string
var value = jsonEncode(obj);
To decode json string to protobuf message, use the following:
var jsonString = ".....";
// decode to json object
var obj = jsonDecode(docJson);
var my_protobuf = MyProtobuf.create()..mergeFromProto3Json(obj);
see https://github.com/google/protobuf.dart/issues/220#issuecomment-863250957

Base64 string reduces after putting Map (data structure) into json.decode(map)

I am converting an Image to base64 and then I am putting it into the Map data structure, but when I convert Map into the JSON string, base64 string reduces and gets the reduced length response from the server. My question is why is Map reducing it?
"Message": "Invalid length for a Base-64 char array or string."
Converting Image file to Base64
var imageBytes = pfImage.readAsBytesSync();
String base64Image = base64Encode(imageBytes);
print("base64 is =$base64Image");
putting into the map
var petData = Map<String, dynamic>();
petData['user_id'] = 55;
petData['name'] = "sdf";
petData['breed'] = "dsf";
petData['StrImageBase64'] =base64Image != null ? base64Image : "";
converting to json string
print("map>>" + json.encode(map));
Some More Info
I have checked it locally as well by putting base64string into map and then print it, the result is in reduced string.
petData['StrImageBase64'] ="/9j/4AAQSkZJRgABAQAAAQABAAD/4RllRXhpZgAASUkqAAgAAAAHABoBBQABAAAAYgAAABsBBQABAAAAagAAACgBAwABAAAAAgAAADIBAgAUAAAAcgAAABMCAwABAAAAAQAAAGmHBAABAAAAhgAAACWIBAABAAAA6AAAACoBAABIAAAAAQAAAEgAAAABAAAAMjAxOToxMToxMCAwNTo1NTozMwAHAACQBwAEAAAAMDIxMAGRBwAEAAAAAQIDAAqSBQABAAAA4AAAAACgBwAEAAAAMDEwMAGgAwABAAAA//8AAAKgBAABAAAAAAUAAAOgBAABAAAAwAMAAAAAAAAkEwAA6AMAAAIABwAFAAMAAAAGAQAAHQACAAsAAAAeAQAAAAAAAAAAAAABAAAANwAAAAEAAAAfAAAAAQAAADIwMTk6MTE6MTAAAAIAAQIEAAEAAABIAQAAAgIEAAEAAAAVGAAAAAAAAP/Y/+AAEEpGSUYAAQEAAAEAAQAA/9sAQwAGBAUGBQQGBgUGBwcGCAoQCgoJCQoUDg8MEBcUGBgXFBYWGh0lHxobIxwWFiAsICMmJykqKRkfLTAtKDAlKCko/9sAQwEHBwcKCAoTCgoTKBoWGigoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgo/8AAEQgA8AFAAwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX2";
print("json.encode =${json.encode(petData)}");
UPDATED
It is not possible, that the map can reduce the value, or Json.decode(map) returns the reduced base64 string, Actually its VS code editor issue for not showing full base64 value.

Google sheets API script

I'm trying to use the following REST API within one of my sheets, and am struggling to return a specific result from the JSON array (first timer here!!)
Here's what I have so far....
function Bittrex_API() {
// Call the Bittrex API for market rates
var response = UrlFetchApp.fetch(
"https://bittrex.com/api/v1.1/public/getmarketsummaries");
// Parse the JSON reply
var json = response.getContentText();
var data = JSON.parse(json);
Logger.log(data);
}
This returns the full array in the Logs, but how do I get it to pull all information from a specific result in the array?
I can return specific results from the first section, by calling the index position "0" as follows:
function Bittrex_API() {
// Call the Bittrex API for market rates
var response = UrlFetchApp.fetch(
"https://bittrex.com/api/v1.1/public/getmarketsummaries");
// Parse the JSON reply
var json = response.getContentText();
var data = JSON.parse(json);
Logger.log(data["result"][0]);
}
But how do I specify a different section of the array without using the index number??
i.e. I want to return all information relating to MarketName=BTC-RCN.
There is nothing wrong with using the index nunber. Whatever notation you use you will need to find BTC-RCN. You can loop through the index number to find it. This will find it and return the results to Sheet1:
function Bittrex_API() {
// Call the Bittrex API for market rates
var response = UrlFetchApp.fetch(
"https://bittrex.com/api/v1.1/public/getmarketsummaries");
// Parse the JSON reply
var json = response.getContentText();
var data = JSON.parse(json);
var lgt=data.result.length
for(i=0;i<lgt;i++){
var test=data["result"][i]["MarketName"]
if(test=="BTC-RCN"){
var num=i;
}
}
var MarketName=data["result"][num]["MarketName"]
var High=data["result"][num]["High"]
var Low=data["result"][num]["Low"]
var Volume=data["result"][num]["Volume"]
var Last=data["result"][num]["Last"]
var BaseVolume=data["result"][num]["BaseVolume"]
var TimeStamp=data["result"][num]["TimeStamp"]
var Bid=data["result"][num]["Bid"]
var Ask=data["result"][num]["Ask"]
var OpenBuyOrders=data["result"][num]["OpenBuyOrders"]
var OpenSellOrders=data["result"][num]["OpenSellOrders"]
var PrevDay=data["result"][num]["PrevDay"]
var Created=data["result"][num]["Created"]
var ss=SpreadsheetApp.getActiveSpreadsheet()
var s=ss.getSheetByName("Sheet1")
s.getRange("A1").setValue("MarketName")
s.getRange("B1").setValue(MarketName)
s.getRange("A2").setValue("High")
s.getRange("B2").setValue(High)
s.getRange("A3").setValue("Low")
s.getRange("B3").setValue(Low)
s.getRange("A4").setValue("Volume")
s.getRange("B4").setValue(Volume)
s.getRange("A5").setValue("Last")
s.getRange("B5").setValue(Last)
s.getRange("A6").setValue("BaseVolume")
s.getRange("B6").setValue(BaseVolume)
s.getRange("A7").setValue("TimeStamp")
s.getRange("B7").setValue(TimeStamp)
s.getRange("A8").setValue("Bid")
s.getRange("B8").setValue(Bid)
s.getRange("A9").setValue("Ask")
s.getRange("B9").setValue(Ask)
s.getRange("A10").setValue("OpenBuyOrders")
s.getRange("B10").setValue(OpenBuyOrders)
s.getRange("A11").setValue("OpenSellOrders")
s.getRange("B11").setValue( OpenSellOrders)
s.getRange("A12").setValue("PrevDay")
s.getRange("B12").setValue(PrevDay)
s.getRange("A13").setValue("Created")
s.getRange("B13").setValue(Created)
}