Export results from JSON in an array

Issue

I want to fetch auto suggestions from Youtube using the following call:

await fetch('https://suggestqueries.google.com/complete/search?client=youtube&ds=yt&q=skrillex&callback=suggestCallback')
.then(response => console.log(response))

This call obtains the following JSON as a result:

"suggestCallback && suggestCallback(["skrillex",[["skrillex",0],["skrillex bangarang",0],["skrillex make it bun dem",0],["skrillex scary monsters and nice sprites",0],["skrillex cinema",0],["skrillex live",0],["skrillex first of the year",0],["skrillex sicko mode",0],["skrillex kyoto",0],["skrillex remix",0]],{"k":1,"q":"bEJKh2TVzWqSICI3U3xEdXTC00g"}])"

I am struggling however to convert this result to an array of the “actual suggestions”. For example, I want to store the JSON obtained above in the following format:

let myArray = ["skrillex", "skrillex bangarang", "skrillex make it bun dem", "skrillex scary monsters and nice sprites", "skrillex cinema", "skrillex live", "skrillex first of the year", "skrillex sicko mode", "skrillex kyoto" ,"skrillex remix"]

What would be a viable solution in order to achieve this?

Solution

One way of doing this would be to use regex to filter a json response out of the response you get, and then create an array from that result.

let jsonp = 'suggestCallback && suggestCallback(["skrillex",[["skrillex",0],["skrillex bangarang",0],["skrillex make it bun dem",0],["skrillex scary monsters and nice sprites",0],["skrillex cinema",0],["skrillex live",0],["skrillex first of the year",0],["skrillex sicko mode",0],["skrillex kyoto",0],["skrillex remix",0]],{"k":1,"q":"bEJKh2TVzWqSICI3U3xEdXTC00g"}])';
    
    let myRe = /\[(.*)\]/g;
    let regExGroups = myRe.exec(jsonp);
    let json = JSON.parse(regExGroups[0]);
    
    let myArray = [];
    
    json[1].forEach((element) => {
    	myArray.push(element[0]);
    });
    
    console.log('suggestions array', myArray);

https://jsfiddle.net/zeonfrost/s7b4aLr6/

But what you really should do is probably define a suggestCallback function what is jsonp

Answered By – Nils Kähler

Answer Checked By – Candace Johnson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.