求助:使用JavaScript解析Coingecko API数据失败
Hey there! Let's fix that parsing issue you're having with the CoinGecko API right away.
Fixing CoinGecko API Data Parsing Failure
The Core Issue
When using jQuery's $.getJSON() method, it automatically parses the JSON response into a ready-to-use JavaScript object/array for you. Your code is trying to run JSON.parse(data) on an already parsed object, which causes a parsing error because JSON.parse() only works with string inputs.
Corrected Code
Here's the fixed version of your code, with explanations of the changes:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $.getJSON("https://api.coingecko.com/api/v3/exchanges", function(data) { // data is already a parsed array of exchange objects—no need to reparse! console.log(data[0]['id']); // Directly access the first exchange's ID }); </script>
Key Fixes Breakdown
- Removed the redundant
var objArray = JSON.parse(data);line: Thedataparameter passed to your callback is already the parsed array of exchange data. - Reordered script tags: Ensured the jQuery library loads before your custom script, so the
$function is available when your code runs.
Verify the Fix
When you run this corrected code, your browser's console should log the ID of the first exchange (typically "binance") without any parsing errors.
内容的提问来源于stack exchange,提问作者Yusuf
相关产品推荐
相关产品推荐

