Home > Net >  Dart Convert HTML to JSON
Dart Convert HTML to JSON

Time:12-15

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?

CodePudding user response:

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