So I want to query the current price of a Stocks with alphvantage. But Alphavantage gets me this back:
{
"Global Quote": {
"01. symbol": "IBM",
"02. open": "201.9400",
"03. high": "205.0500",
"04. low": "201.4300",
"05. price": "203.5300",
"06. volume": "3705004",
"07. latest trading day": "2024-09-09",
"08. previous close": "200.7400",
"09. change": "2.7900",
"10. change percent": "1.3899%"
}
}
Does anyone know how I can filter it to only get the number of the current price as output? Heres the script:
<template>
<div class="bg-gray-900 min-h-screen">
<p class="text-gray-100 text-xl">
{{stock}}
</p>
</div>
</template>
<script>
export default {
async asyncData ({ $axios }) {
const stock = await $axios.$get('https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=IBM&apikey=****')
return { stock }
}
}
</script>
Querying a specific value of a stock with axios and alphavantage in NuxtJS
You don't need to adjust the query when the result you need is included in the larger JSON object which you can access with stock['Global Quote']['05. price']
. Here is some documentation on bracket notation property access.
You can also iterate over the key-value pairs just in case the order is not guaranteed
function getPrice(stock) {
for (const [key, value] of Object.entries(stock['Global Quote'])) {
if (key.includes('price')) {
return value
}
}
return null // price not found
}
const price = getPrice(stock)