I am new with typescript and developing and was wondering if you could help me.
I have a simple piece of code to fetch data from a website which "works" the only problem is to get the actual data under object data.token.
this is the site: https://gmgn.ai/defi/quotation/v1/tokens/sol/EV1k3kQwueeD3uYr3wMzeydYc94qqrpjfHdCNVs2A22d
How can I change the code to get only the JSON response (at the end of this response example) data.token.symbol and Name?
The code returns this:
const axios = require('axios')
axios.get('https://gmgn.ai/defi/quotation/v1/tokens/sol/EV1k3kQwueeD3uYr3wMzeydYc94qqrpjfHdCNVs2A22d')
.then(res => {console.log(res)
})
{
status: 200,
statusText: 'OK',
headers: Object [AxiosHeaders] {
'content-type': 'application/json; charset=utf-8',
'transfer-encoding': 'chunked',
connection: 'keep-alive',
vary: 'Accept-Encoding',
date: 'Thu, 27 Jun 2024 14:11:30 GMT',
'x-powered-by': 'Express',
etag: 'W/"bd4-nznvf3ajmxpg+hguX8CIbl0VXdQ"',
'x-envoy-upstream-service-time': '36',
server: 'istio-envoy',
'x-cache': 'Miss from cloudfront',
via: '1.1 459ec09472abb8544521a9b5cc6706ce.cloudfront.net (CloudFront)',
'x-amz-cf-pop': 'AMS58-P5',
'x-amz-cf-id': 'h1W08tqCuJTIf8fsKFjnWRoYvkYzSSND3ZCH36AzgQax8msy3Mj6Jw==',
'x-xss-protection': '1; mode=block',
'x-frame-options': 'SAMEORIGIN',
'referrer-policy': 'strict-origin-when-cross-origin',
'x-content-type-options': 'nosniff',
'strict-transport-security': 'max-age=31536000'
},
config: {
transitional: {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: false
},
adapter: [ 'xhr', 'http', 'fetch' ],
transformRequest: [ [Function: transformRequest] ],
transformResponse: [ [Function: transformResponse] ],
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
env: { FormData: [Function], Blob: [class Blob] },
validateStatus: [Function: validateStatus],
headers: Object [AxiosHeaders] {
Accept: 'application/json, text/plain, */*',
'Content-Type': undefined,
'User-Agent': 'axios/1.7.2',
'Accept-Encoding': 'gzip, compress, deflate, br'
},
method: 'get',
url: 'https://gmgn.ai/defi/quotation/v1/tokens/sol/EV1k3kQwueeD3uYr3wMzeydYc94qqrpjfHdCNVs2A22d',
data: undefined
},
request: <ref *1> ClientRequest {
_events: [Object: null prototype] {
abort: [Function (anonymous)],
aborted: [Function (anonymous)],
connect: [Function (anonymous)],
error: [Function (anonymous)],
socket: [Function (anonymous)],
timeout: [Function (anonymous)],
finish: [Function: requestOnFinish]
},
_eventsCount: 7,
_maxListeners: undefined,
outputData: [],
outputSize: 0,
writable: true,
destroyed: true,
_last: true,
chunkedEncoding: false,
shouldKeepAlive: true,
maxRequestsOnConnectionReached: false,
_defaultKeepAlive: true,
useChunkedEncodingByDefault: false,
sendDate: false,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
strictContentLength: false,
_contentLength: 0,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
_closed: true,
socket: TLSSocket {
_tlsOptions: [Object],
_secureEstablished: true,
_securePending: false,
_newSessionPending: false,
_controlReleased: true,
secureConnecting: false,
_SNICallback: null,
servername: 'gmgn.ai',
alpnProtocol: false,
authorized: true,
authorizationError: null,
encrypted: true,
_events: [Object: null prototype],
_eventsCount: 9,
connecting: false,
_hadError: false,
_parent: null,
_host: 'gmgn.ai',
_closeAfterHandlingError: false,
_readableState: [ReadableState],
_writableState: [WritableState],
allowHalfOpen: false,
_maxListeners: undefined,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: undefined,
_server: null,
ssl: [TLSWrap],
_requestCert: true,
_rejectUnauthorized: true,
timeout: 5000,
parser: null,
_httpMessage: null,
autoSelectFamilyAttemptedAddresses: [Array],
[Symbol(alpncallback)]: null,
[Symbol(res)]: [TLSWrap],
[Symbol(verified)]: true,
[Symbol(pendingSession)]: null,
[Symbol(async_id_symbol)]: -1,
[Symbol(kHandle)]: [TLSWrap],
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: Timeout {
_idleTimeout: 5000,
_idlePrev: [TimersList],
_idleNext: [TimersList],
_idleStart: 378,
_onTimeout: [Function: bound ],
_timerArgs: undefined,
_repeat: null,
_destroyed: false,
[Symbol(refed)]: false,
[Symbol(kHasPrimitive)]: false,
[Symbol(asyncId)]: 26,
[Symbol(triggerId)]: 24
},
[Symbol(kBuffer)]: null,
[Symbol(kBufferCb)]: null,
[Symbol(kBufferGen)]: null,
[Symbol(shapeMode)]: true,
[Symbol(kCapture)]: false,
[Symbol(kSetNoDelay)]: false,
[Symbol(kSetKeepAlive)]: true,
[Symbol(kSetKeepAliveInitialDelay)]: 1,
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0,
[Symbol(connect-options)]: [Object]
},
_header: 'GET /defi/quotation/v1/tokens/sol/EV1k3kQwueeD3uYr3wMzeydYc94qqrpjfHdCNVs2A22d HTTP/1.1rn' +
'Accept: application/json, text/plain, */*rn' +
'User-Agent: axios/1.7.2rn' +
'Accept-Encoding: gzip, compress, deflate, brrn' +
'Host: gmgn.airn' +
'Connection: keep-alivern' +
'rn',
_keepAliveTimeout: 0,
_onPendingData: [Function: nop],
agent: Agent {
_events: [Object: null prototype],
_eventsCount: 2,
_maxListeners: undefined,
defaultPort: 443,
protocol: 'https:',
options: [Object: null prototype],
requests: [Object: null prototype] {},
sockets: [Object: null prototype] {},
freeSockets: [Object: null prototype],
keepAliveMsecs: 1000,
keepAlive: true,
maxSockets: Infinity,
maxFreeSockets: 256,
scheduling: 'lifo',
maxTotalSockets: Infinity,
totalSocketCount: 1,
maxCachedSessions: 100,
_sessionCache: [Object],
[Symbol(shapeMode)]: false,
[Symbol(kCapture)]: false
},
socketPath: undefined,
method: 'GET',
maxHeaderSize: undefined,
insecureHTTPParser: undefined,
joinDuplicateHeaders: undefined,
path: '/defi/quotation/v1/tokens/sol/EV1k3kQwueeD3uYr3wMzeydYc94qqrpjfHdCNVs2A22d',
_ended: true,
res: IncomingMessage {
_events: [Object],
_readableState: [ReadableState],
_maxListeners: undefined,
socket: null,
httpVersionMajor: 1,
httpVersionMinor: 1,
httpVersion: '1.1',
complete: true,
rawHeaders: [Array],
rawTrailers: [],
joinDuplicateHeaders: undefined,
aborted: false,
upgrade: false,
url: '',
method: null,
statusCode: 200,
statusMessage: 'OK',
client: [TLSSocket],
_consuming: true,
_dumped: false,
req: [Circular *1],
_eventsCount: 4,
responseUrl: 'https://gmgn.ai/defi/quotation/v1/tokens/sol/EV1k3kQwueeD3uYr3wMzeydYc94qqrpjfHdCNVs2A22d',
redirects: [],
[Symbol(shapeMode)]: true,
[Symbol(kCapture)]: false,
[Symbol(kHeaders)]: [Object],
[Symbol(kHeadersCount)]: 38,
[Symbol(kTrailers)]: null,
[Symbol(kTrailersCount)]: 0
},
aborted: false,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
reusedSocket: false,
host: 'gmgn.ai',
protocol: 'https:',
_redirectable: Writable {
_events: [Object],
_writableState: [WritableState],
_maxListeners: undefined,
_options: [Object],
_ended: true,
_ending: true,
_redirectCount: 0,
_redirects: [],
_requestBodyLength: 0,
_requestBodyBuffers: [],
_eventsCount: 3,
_onNativeResponse: [Function (anonymous)],
_currentRequest: [Circular *1],
_currentUrl: 'https://gmgn.ai/defi/quotation/v1/tokens/sol/EV1k3kQwueeD3uYr3wMzeydYc94qqrpjfHdCNVs2A22d',
[Symbol(shapeMode)]: true,
[Symbol(kCapture)]: false
},
[Symbol(shapeMode)]: false,
[Symbol(kCapture)]: false,
[Symbol(kBytesWritten)]: 0,
[Symbol(kNeedDrain)]: false,
[Symbol(corked)]: 0,
[Symbol(kOutHeaders)]: [Object: null prototype] {
accept: [Array],
'user-agent': [Array],
'accept-encoding': [Array],
host: [Array]
},
[Symbol(errored)]: null,
[Symbol(kHighWaterMark)]: 16384,
[Symbol(kRejectNonStandardBodyWrites)]: false,
[Symbol(kUniqueHeaders)]: null
},
data: {
code: 0,
msg: 'success',
** data: { token: [Object], **vote: [Object], my_vote: [Object] }
}
}
I couldn’t get pass this problem unfortunately
2
Answers
to get whatever data you want out of the response you just have to index into it and get what you want. Since you’re new to programming it can seem a bit difficult but in javascript its probably one of the simplest, and in general indexing into different data structures is not too hard.
Basically when dealing with json and javascript, its quite easy and they work very well together since json stands for JavaScript Object Notation. And basically the only types of variables are primitives (number, string, boolean) and then I guess compound types that are either objects or arrays. I think this is mostly right, it’s a basic explanation but I think it’s got whats most useful.
So what we care about for this example is mainly the objects and arrays.
You can index into objects using the key of the object. So if you have
then
will return
"hi"
And for multiple indices
will return "hello"
For arrays its very similar, in reality arrays are mostly just objects with number keys, but to index them you use
[<index>]
. So given dataFor indices 0 and 2 for example, you get the following
So in your case, you’re more interested in objects since the response is all objects. Following this, from the return on https://gmgn.ai/defi/quotation/v1/tokens/sol/EV1k3kQwueeD3uYr3wMzeydYc94qqrpjfHdCNVs2A22d
Doing
Should work.