Home > Software design >  Accessing nested JSON from google knowledge API with dart
Accessing nested JSON from google knowledge API with dart

Time:11-19

I'm sorry if this has been asked before (I've searched for this exactly, but still can't figure it out). I am trying to access a nested element from the google knowledge graph API. Here is what the JSON looks like

{
  "@context": {
    "goog": "http://schema.googleapis.com/",
    "kg": "http://g.co/kg",
    "EntitySearchResult": "goog:EntitySearchResult",
    "resultScore": "goog:resultScore",
    "@vocab": "http://schema.org/",
    "detailedDescription": "goog:detailedDescription"
  },
  "@type": "ItemList",
  "itemListElement": [
    {
      "result": {
        "name": "Samoyed",
        "description": "Dog breed",
        "@type": [
          "Thing"
        ],
        "@id": "kg:/m/017lg8",
        "detailedDescription": {
          "url": "https://en.wikipedia.org/wiki/Samoyed_dog",
          "articleBody": "The Samoyed is a breed of medium-sized herding dogs with thick, white, double-layer coats. They are a spitz-type dog which takes its name from the Samoyedic peoples of Siberia.",
          "license": "https://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License"
        }
      },
      "@type": "EntitySearchResult",
      "resultScore": 7775.93505859375
    }
  ]
}

I need to access the articleBody element. Here is what is what I have got so far in dart:

Future<Dog> getWikiInfo() async {
  var query = "Samoyed";
  var API_KEY = "*************";
  final apiURL =
      "https://kgsearch.googleapis.com/v1/entities:search?query=$query&key=$API_KEY&limit=1&indent=True";
  final response = await http.get(Uri.parse(apiURL));

  if (response.statusCode == 200) {
    for (var element in json.decode(response.body)['itemListElement']) {
      for (var subelement
          in json.decode(response.body)['detailedDescription']) {
        print(subelement['articleBody']);
      }
    }
  }

I've been trying different iterations of this to try and return that element. Here is what my Dog Class looks looks like.

class Dog {
  final String link;
  final String breed;
  final String info;
  Dog({this.link, this.breed, this.info});

  factory Dog.fromJson(Map<String, dynamic> json) {
    return Dog(
        breed: json['message'],
        link: json['message'],
        info: json['articleBody']);
  }
}

CodePudding user response:

try this sequence code as per your logic

json.decode(response.body)["itemListElement"][0]["result"]["detailedDescription"]
  • Related