I cannot find a way to print a JSON Value - javascript

{ "data": { "time": { "updated": "May 20, 2022 07:29:00 UTC", "updatedISO": "2022-05-20T07:29:00+00:00", "updateduk": "May 20, 2022 at 08:29 BST" }, "disclaimer": "This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchangerates.org", "chartName": "Bitcoin", "bpi": { "USD": { "code": "USD", "symbol": "$", "rate": "30,177.6870", "description": "United States Dollar", "rate_float": 30177.687 }, "GBP": { "code": "GBP", "symbol": "£", "rate": "24,661.9301", "description": "British Pound Sterling", "rate_float": 24661.9301 }, "EUR": { "code": "EUR", "symbol": "€", "rate": "29,026.2574", "description": "Euro", "rate_float": 29026.2574 } } }, "status": 200, "statusText": "", "headers": { "cache-control": "max-age=15", "content-length": "678", "content-type": "application/javascript", "expires": "Fri, 20 May 2022 07:30:07 UTC" }, "config": { "transformRequest": {}, "transformResponse": {}, "timeout": 0, "xsrfCookieName": "XSRF-TOKEN", "xsrfHeaderName": "X-XSRF-TOKEN", "maxContentLength": -1, "headers": { "Accept": "application/json, text/plain, */*" }, "method": "get", "url": "https://api.coindesk.com/v1/bpi/currentprice.json" }, "request": {} }
I have this JSON object that prints the information about currencies. I am trying to get the data for a specfic currency that is USD.
When I type JSON.data.bpi.USD it says UNDEFINED. I need help with this.

Before you use it you need to parse it like this:
const myObject = JSON.parse(/* your object here */)
console.log(myObject.data.bpi.USD)
// it is ready now

You can access to your object properties with Property accessor dot notation:
const obj = { "data": { "time": { "updated": "May 20, 2022 07:29:00 UTC", "updatedISO": "2022-05-20T07:29:00+00:00", "updateduk": "May 20, 2022 at 08:29 BST" }, "disclaimer": "This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchangerates.org", "chartName": "Bitcoin", "bpi": { "USD": { "code": "USD", "symbol": "$", "rate": "30,177.6870", "description": "United States Dollar", "rate_float": 30177.687 }, "GBP": { "code": "GBP", "symbol": "£", "rate": "24,661.9301", "description": "British Pound Sterling", "rate_float": 24661.9301 }, "EUR": { "code": "EUR", "symbol": "€", "rate": "29,026.2574", "description": "Euro", "rate_float": 29026.2574 } } }, "status": 200, "statusText": "", "headers": { "cache-control": "max-age=15", "content-length": "678", "content-type": "application/javascript", "expires": "Fri, 20 May 2022 07:30:07 UTC" }, "config": { "transformRequest": {}, "transformResponse": {}, "timeout": 0, "xsrfCookieName": "XSRF-TOKEN", "xsrfHeaderName": "X-XSRF-TOKEN", "maxContentLength": -1, "headers": { "Accept": "application/json, text/plain, */*" }, "method": "get", "url": "https://api.coindesk.com/v1/bpi/currentprice.json" }, "request": {} }
console.log(obj.data.bpi.USD)

Related

mongodb find query is not working

I have a collection facialAnalysisConfiguration
the data in the collection is as shown below
{
"details": {
"date": ISODate("2018-04-03T11:54:53.916+0000"),
"statusText": "OK",
"config": {
"headers": {
"Content-Type": "application/json;charset=utf-8",
"Accept": "application/json, text/plain, */*"
},
"data": {
"image": ""
},
"url": "/storeIncommingImages",
"jsonpCallbackParam": "callback",
"transformResponse": [
null
],
"transformRequest": [
null
],
"method": "POST"
},
"status": NumberInt(200),
"data": {
"FaceModelVersion": "2.0",
"OrientationCorrection": "ROTATE_0",
"FaceRecords": [{
"FaceDetail": {
"Confidence": 99.9393310546875,
"Quality": {
"Sharpness": 99.80813598632812,
"Brightness": 12.500774383544922
},
"Pose": {
"Pitch": -5.199888229370117,
"Yaw": -3.2905712127685547,
"Roll": 7.3970136642456055
},
"Emotions": [{
"Confidence": 44.84807205200195,
"Type": "CONFUSED"
},
{
"Confidence": 17.345977783203125,
"Type": "CALM"
},
{
"Confidence": 6.819361686706543,
"Type": "SURPRISED"
}
],
"MouthOpen": {
"Confidence": 99.90953826904297,
"Value": false
},
"EyesOpen": {
"Confidence": 99.79545593261719,
"Value": true
},
"Mustache": {
"Confidence": 99.68254852294922,
"Value": false
},
"Beard": {
"Confidence": 95.8907470703125,
"Value": false
},
"Gender": {
"Confidence": 99.9259262084961,
"Value": "Male"
},
"Sunglasses": {
"Confidence": 99.36517333984375,
"Value": false
},
"Eyeglasses": {
"Confidence": 99.82603454589844,
"Value": true
},
"Smile": {
"Confidence": 50.894676208496094,
"Value": false
},
"AgeRange": {
"High": NumberInt(15),
"Low": NumberInt(10)
},
"BoundingBox": {
"Top": 0.4294871687889099,
"Left": 0.29567307233810425,
"Height": 0.39743590354919434,
"Width": 0.30048078298568726
}
},
"Face": {
"Confidence": 99.9393310546875,
"ExternalImageId": "belgium_medium_gender",
"ImageId": "65e5b4f0-f803-5592-9c7c-95d3b983290b",
"BoundingBox": {
"Top": 0.4294871687889099,
"Left": 0.29567307233810425,
"Height": 0.39743590354919434,
"Width": 0.30048078298568726
},
"FaceId": "a875fb3b-4257-4cf0-951b-3d4892aabe41"
}
}]
}
},
"__v": NumberInt(0)
}
how to get all the records where the Emotions.type value is "CONFUSED"
please note the object navigation is as shown below details.data.FaceRecords[0].FaceDetail.Confidence
Tried writing few quires using aggregation but unable to find please suggest a way to approach it
I see conflicts in your description. You have mentioned that you want to get all the records where the Emotions.type value is "CONFUSED" but later have specified a object navigation (FaceDetail.Confidence).
Regardless, the below query should return all the matching records whose Emotions.Type is CONFUSED.
db.facialAnalysisConfiguration.find( { "details.data.FaceRecords.FaceDetail.Emotions.Type": "CONFUSED" }

Foursquare not returning all attributes from a search

I'm making requests to Foursquare using
GET https://api.foursquare.com/v2/venues/search
in an attempt to get the "price" attribute. However, it doesn't seem to return all the listed attributes that this docs page details.
https://developer.foursquare.com/docs/api/venues/search
This is the object that I am receiving:
id: '4c93ae9594a0236aea808512',
name: 'China Garden',
contact: {},
location: [Object],
categories: [Array],
verified: false,
stats: [Object],
hasMenu: true,
menu: [Object],
allowMenuUrlEdit: true,
beenHere: [Object],
specials: [Object],
referralId: 'v-1516988384',
venueChains: [],
hasPerk: false
As you can see, the price attribute (along with some others) is not part of the response object. These are also the parameters I'm using to make the search:
var params = {
"near": "exmouth uk",
"categoryId": catID,
"intent": "browse",
"limit": 50,
"time": "any",
"day": "any",
};
Does anybody know why these are the only attributes that are returned?
There's a new /search/recommendations endpoint that sounds like it will do what you want.
For one, it allows querying on params like near, categoryId, limit, localTime, localDay, and more.
And the response contains price, and more.
Here's an example of a response:
[{
"displayType": "venue",
"venue": {
"id": "4fa445c8e4b0baf7cc71e811",
"name": "Boudoir",
"contact": {
"phone": "+441382225968",
"formattedPhone": "+44 1382 225968"
},
"location": {
"address": "1 Temple Lane",
"lat": 56.459587391243105,
"lng": -2.978718040375153,
"labeledLatLngs": [{
"label": "display",
"lat": 56.459587391243105,
"lng": -2.978718040375153
}],
"postalCode": "DD1 4HA",
"cc": "GB",
"city": "Dundee",
"state": "Dundee City",
"country": "United Kingdom",
"formattedAddress": [
"1 Temple Lane",
"Dundee",
"Dundee City",
"DD1 4HA",
"United Kingdom"
]
},
"categories": [{
"id": "4bf58dd8d48988d146941735",
"name": "Deli / Bodega",
"pluralName": "Delis / Bodegas",
"shortName": "Deli / Bodega",
"icon": {
"prefix": "https://ss3.4sqi.net/img/categories_v2/food/deli_",
"suffix": ".png"
},
"primary": true
}],
"verified": false,
"stats": {
"checkinsCount": 73,
"usersCount": 46,
"tipCount": 0
},
"url": "http://www.boudoir.wickedweb.biz",
"price": {
"tier": 3,
"message": "Expensive",
"currency": "£"
},
"dislike": false,
"ok": false,
"allowMenuUrlEdit": true,
"beenHere": {
"count": 0,
"marked": false,
"lastCheckinExpiredAt": 0
}
},
"id": "5a86bea63b830731dbaff394",
"photo": {
"id": "51d8959a498ebc1f8cfe6ca1",
"createdAt": 1373148570,
"prefix": "https://igx.4sqi.net/img/general/",
"suffix": "/2773213_EBnYq-AmD-arj7VH3pP47B7HMi1lP2LYdb76CSsJJ9o.jpg",
"width": 720,
"height": 960,
"visibility": "public"
},
"snippets": {
"count": 1,
"items": [{}]
}
}]

How to extract items from json objects using javascript

This is the json object I get after running a script.
{
"log": {
"entries": [{
"startedDateTime": "2015-08-16T10:27:35.264Z",
"time": 35,
"request": {
"method": "GET",
"url": "http://www.google.com/",
"httpVersion": "HTTP/1.1",
"cookies": [],
"headers": [{
"name": "User-Agent",
"value": "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/534.34 (KHTML, like Gecko) PhantomJS/1.9.8 Safari/534.34"
}, {
"name": "Accept",
"value": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
}],
"queryString": [],
"headersSize": -1,
"bodySize": -1
},
"response": {
"status": 302,
"statusText": "Found",
"httpVersion": "HTTP/1.1",
"cookies": [],
"headers": [{
"name": "Cache-Control",
"value": "private"
}, {
"name": "Content-Type",
"value": "text/html; charset=UTF-8"
}, {
"name": "Location",
"value": "http://www.google.co.in/?gfe_rd=cr&ei=mWXQVZiNLaHv8wehp6jYDw"
}, {
"name": "Content-Length",
"value": "261"
}, {
"name": "Date",
"value": "Sun, 16 Aug 2015 10:27:37 GMT"
}, {
"name": "Server",
"value": "GFE/2.0"
}, {
"name": "Connection",
"value": "keep-alive"
}],
"redirectURL": "",
"headersSize": -1,
"bodySize": 261,
"content": {
"size": 261,
"mimeType": "text/html; charset=UTF-8"
}
},
"cache": {},
"timings": {
"blocked": 0,
"dns": -1,
"connect": -1,
"send": 0,
"wait": 35,
"receive": 0,
"ssl": -1
},
"pageref": "http://www.google.com"
}, .....
]
}
}
In my javascript, I am trying to access every object. But its not working.
Lets say for example, I assign this json object to data:
data = JSON.parse({... that whole json object...});
console.log(data["log"]["entries"][0]);
I get nothing. I am using this inside node. What mistake am I doing here ?
You should treat this as object, here is a working fiddle :
https://jsfiddle.net/8jqvvmc6/3/
var jsonData = {
"log": {
"entries": [{
"startedDateTime": "2015-08-16T10:27:35.264Z",
"time": 35,
"request": {
"method": "GET",
"url": "http://www.google.com/",
"httpVersion": "HTTP/1.1",
"cookies": [],
"headers": [{
"name": "User-Agent",
"value": "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/534.34 (KHTML, like Gecko) PhantomJS/1.9.8 Safari/534.34"
}, {
"name": "Accept",
"value": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
}],
"queryString": [],
"headersSize": -1,
"bodySize": -1
},
"response": {
"status": 302,
"statusText": "Found",
"httpVersion": "HTTP/1.1",
"cookies": [],
"headers": [{
"name": "Cache-Control",
"value": "private"
}, {
"name": "Content-Type",
"value": "text/html; charset=UTF-8"
}, {
"name": "Location",
"value": "http://www.google.co.in/?gfe_rd=cr&ei=mWXQVZiNLaHv8wehp6jYDw"
}, {
"name": "Content-Length",
"value": "261"
}, {
"name": "Date",
"value": "Sun, 16 Aug 2015 10:27:37 GMT"
}, {
"name": "Server",
"value": "GFE/2.0"
}, {
"name": "Connection",
"value": "keep-alive"
}],
"redirectURL": "",
"headersSize": -1,
"bodySize": 261,
"content": {
"size": 261,
"mimeType": "text/html; charset=UTF-8"
}
},
"cache": {},
"timings": {
"blocked": 0,
"dns": -1,
"connect": -1,
"send": 0,
"wait": 35,
"receive": 0,
"ssl": -1
},
"pageref": "http://www.google.com"
}]
}
};
alert(jsonData["log"]["entries"][0]);
See the fiddle to see how it should work in your case. Also I assume data should be a local variable, it might get overwritten somewhere before your code executes. Don't pollute the global scope I guess.
That does not work!
data = JSON.parse({... that whole json object...});
because
data = {... that whole json object...};
is already an object.
But if you have
data = JSON.parse('{... that whole json object...}');
then it should be parsed first, to convert a string to an JSON compliant object.

How to parse JSON from Gmail API using JavaScript?

Using JavaScript, how do I extract the Date, To, From, Subject and Text fields from the Gmail API's return (see below)?
It's not in the usual name-value pair, at least not how I would do it with JSON. Also, the text needs to be decoded.
{
"id": "rthrt34t34t45g45g4",
"threadId": "gg54tgw4y45t24f3f",
"labelIds": [
"SENT"
],
"snippet": "Testing 1 2 3",
"historyId": "2344",
"payload": {
"mimeType": "multipart/alternative",
"filename": "",
"headers": [
{
"name": "MIME-Version",
"value": "1.0"
},
{
"name": "Received",
"value": "by 101.64.82.199 with HTTP; Wed, 18 Feb 2015 21:34:49 -0800 (PST)"
},
{
"name": "Date",
"value": "Thu, 19 Feb 2015 12:34:49 +0700"
},
{
"name": "Delivered-To",
"value": "test#test.org"
},
{
"name": "Message-ID",
"value": "<retert-_RKS0Vc-U6-V8dSma5=ertertertertf2e#mail.gmail.com>"
},
{
"name": "Subject",
"value": "testing 123"
},
{
"name": "From",
"value": "A Test <test#test.org>"
},
{
"name": "To",
"value": "test.test#test.com"
},
{
"name": "Content-Type",
"value": "multipart/alternative; boundary=egrreg34t34"
}
],
"body": {
"size": 0
},
"parts": [
{
"partId": "0",
"mimeType": "text/plain",
"filename": "",
"headers": [
{
"name": "Content-Type",
"value": "text/plain; charset=UTF-8"
}
],
"body": {
"size": 8,
"data": "MTIzNDU2DQo="
}
},
{
"partId": "1",
"mimeType": "text/html",
"filename": "",
"headers": [
{
"name": "Content-Type",
"value": "text/html; charset=UTF-8"
}
],
"body": {
"size": 29,
"data": "PGRpdiBkaXI9Imx0ciI-MTIzNDU2PC9kaXY-DQo="
}
}
]
},
"sizeEstimate": 651
}
Surfing on the Internet I have found this class which describes a Generic GMail Message. You might use this to easily parse the JSON (by using any of the wide range of provided libraries).
you can use e.g. filter function as follows:
var extractField = function(json, fieldName) {
return json.payload.headers.filter(function(header) {
return header.name === fieldName;
})[0];
};
var date = extractField(response, "Date");
var subject = extractField(response, "Subject");
Does this help?

How to read the stripe webhook response [duplicate]

This question already has an answer here:
Receive and log webhook post
(1 answer)
Closed 8 years ago.
I have created the coldfusion file to catch the STRIPE webhook response.
<cfsavecontent variable="headerdump">
<cfdump var="#toString(getHttpRequestData().content, 'utf-8')#" expand="yes" format="text">
</cfsavecontent>
When i print the headerdump, got the below response. I want to extract the node values of the output text.
<pre>{
"id": "evt_1041EO45YXiN2y2zPhZbNrgh",
"created": 1399872268,
"livemode": false,
"type": "invoice.payment_succeeded",
"data": {
"object": {
"date": 1399872268,
"id": "in_1041EO45YXiN2y2zQF1xhLyl",
"period_start": 1399872268,
"period_end": 1399872268,
"lines": {
"object": "list",
"total_count": 1,
"has_more": false,
"url": "/v1/invoices/in_1041EO45YXiN2y2zQF1xhLyl/lines",
"data": [
{
"id": "sub_41EOmzNFelCyAL",
"object": "line_item",
"type": "subscription",
"livemode": false,
"amount": 0,
"currency": "usd",
"proration": false,
"period": {
"start": 1399872268,
"end": 1399958668
},
"quantity": 1,
"plan": {
"interval": "month",
"name": "test one day",
"created": 1399536505,
"amount": 500,
"currency": "usd",
"id": "test_001",
"object": "plan",
"livemode": false,
"interval_count": 1,
"trial_period_days": 1,
"metadata": {
},
"statement_description": "half day trial"
},
"description": null,
"metadata": null
}
]
},
"subtotal": 0,
"total": 0,
"customer": "cus_41EOvhzjYGx7ci",
"object": "invoice",
"attempted": true,
"closed": true,
"paid": true,
"livemode": false,
"attempt_count": 0,
"amount_due": 0,
"currency": "usd",
"starting_balance": 0,
"ending_balance": null,
"next_payment_attempt": null,
"charge": null,
"discount": null,
"application_fee": null,
"subscription": "sub_41EOmzNFelCyAL",
"metadata": {
},
"description": null
}
},
"object": "event",
"pending_webhooks": 1,
"request": "iar_41EO1vDF1gpnPn"
}</pre>
Please suggest how to read this either in coldfusion or javascript.
Thanks
I do something like this:
<cfscript>
variables.requestdata = getHTTPRequestData();
variables.sStripeData = toString(variables.requestdata.content);
variables.stStripeData = deserializeJSON(variables.sStripeData);
</cfscript>

Categories