3

I am building a YT mp3 downloader. I'm using API from youtubeinmp3. This is how I am getting the download link in JSON format.

JSON data from API?

I am using this to assign the JSON value for "link" to JS Variable ytdlink. But it's not working, the value for ytdlink is getting set to "function link() { [native code] }".

function getyt()
            {
            var a = document.getElementById("mquery").value;
                $.get(
                    "http://www.youtubeinmp3.com/fetch/?format=JSON",
                    {
                        video:a
                    },function(data) {
                    console.log(data);
                    var ytdlink = data.link;
                    });

            }

How do I assign the link to a JS variable?

7
  • 1
    $.get has a fourth parameter "dataType" which you should set to "json". Right now you're getting a string. Commented Apr 12, 2017 at 18:02
  • @James It should be intelligently guessing and converting it to JSON already as per the docs Commented Apr 12, 2017 at 18:06
  • @mhodges It should be, but it's not. Why in your answer are you suggesting to separately parse the string to an object if it should already be done? Commented Apr 12, 2017 at 18:13
  • @James My previous comment was more-so inquisitive of why it was not automatically converting it. I wonder if it has to do with the escaped characters in the link value? I'm honestly not sure.. Commented Apr 12, 2017 at 18:18
  • 1
    youtubeinmp3.com is returning a Content-Type of text/html instead of application/json, is probably why. Note that setting json using the fourth parameter will force the conversion. Commented Apr 12, 2017 at 18:30

1 Answer 1

2

Since link is a function on the String prototype and you are working with a JSON string, that is why it is spitting out

function link() { [native code] }

You must use JSON.parse() on your data in order to access the properties like so:

var obj = JSON.parse(data);
var ytdlink = obj.link;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.