0

I'm trying to use AJAX to gather search results from DuckDuckGo's Search API.

Here's the JavaScript I've written so far:

$.ajax({
  type: 'GET',
  url: 'https://api.duckduckgo.com/',
  data: { q: myhomestate, format: 'json', pretty: 1 },
  jsonpCallback: 'jsonp',
  listLocation: "RelatedTopics",
  dataType: 'text'
}).then(function (data) {
    console.log(data);
});
}

The code works fine, but it just returns a big JSON object, and I don't know how to select any of its elements. Please help!

Seth Connell
  • 867
  • 1
  • 9
  • 12

2 Answers2

2

data = JSON.parse(data);

turns it into a normal JavaScript object. Then you can select elements like you would any other object.


e.g.

var heading = data.Heading;

var developer = data.meta.developer[0].name

SamVK
  • 3,077
  • 1
  • 14
  • 19
1

First you need to convert JSON response into JSON Object, as shown below :

var jsonObj = JSON.parse(data);

Then you can access, it's fields as shown below :

console.log(jsonObj["RelatedTopics"]);
Nishesh Pratap Singh
  • 2,131
  • 2
  • 13
  • 20