Home > database >  Get Value from Random Key in JSON
Get Value from Random Key in JSON

Time:12-08

I'm making a simple application with http requests. I managed to get back the result from first API(Google Translate). But I can't get any results from second one.

The API I'm trying to get result: https://tr.wikipedia.org/w/api.php?action=query&prop=description&format=json&titles=masa

The output is:

{
    "batchcomplete": "",
    "query": {
        "normalized": [
            {
                "from": "masa",
                "to": "Masa"
            }
        ],
        "pages": {
            "219000": {
                "pageid": 219000,
                "ns": 0,
                "title": "Masa",
                "description": "\u00fcst\u00fc d\u00fcz mobilya",
                "descriptionsource": "central"
            }
        }
    }
}

As you can see every time when I request something 'pageid' is changing and I can't declare any keys for this JSON.

My Flutter Code:

var transurl = Uri.parse(
        'https://translation.googleapis.com/language/translate/v2?key=AIzaSyCZ**YCKlw');
    var response = await http.post(transurl,
        body: {'q': sonuc, 'source': 'en', 'target': 'tr', 'format': 'text'});
    if (response.statusCode == 200) {
      var harita = jsonDecode(utf8.decode(response.bodyBytes)) as Map;
      var ceviri = harita['data']['translations'].last['translatedText'];
      print(ceviri);
      var wikiurl = Uri.parse(
          'https://tr.wikipedia.org/w/api.php?action=query&prop=description&format=json&titles=$ceviri');
      var wikii = await http.post(wikiurl, body: {});
      print(wikii);
      var wikibilgi = jsonDecode(utf8.decode(wikii.bodyBytes)) as Map;
      var wikiii = (wikibilgi['query']['pages']); //Don't know what to write here.
//Don't know what to write here.
      print(wikiii);
      Navigator.push(
          context,
          MaterialPageRoute(
              builder: (context) =>
                  BilgiEkrani(sonuc: sonuc, oran: oran, wikibilgi: wikiii)));
    } else {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(
          content: Text("GOOGLE TRANSLATE API HATASI"),
          duration: const Duration(seconds: 2)));
    }
  }

CodePudding user response:

You can get the first key of the map (your pageid) with:

var wikipageId = wikibilgi['query']['pages'].keys.toList()[0]; 

To get the content, you can then just use that key.

var wikiii = wikibilgi['query']['pages'][wikipageId];
  • Related