I am having difficulty with a pulling some data from an API for a school project using Jquery.
If I use the following coinmaketcap API I get the following response
https://api.coinmarketcap.com/v1/ticker/bitcoin/
[
{
"id": "bitcoin",
"name": "Bitcoin",
"symbol": "BTC",
"rank": "1",
"price_usd": "8854.92",
"price_btc": "1.0",
"24h_volume_usd": "6759730000.0",
"market_cap_usd": "150480289107",
"available_supply": "16993975.0",
"total_supply": "16993975.0",
"max_supply": "21000000.0",
"percent_change_1h": "-0.13",
"percent_change_24h": "0.12",
"percent_change_7d": "8.3",
"last_updated": "1524459272"
}
]
I get am able to get the symbol for Bitcoin and place it into a variable by using this code
> $.getJSON('https://api.coinmarketcap.com/v1/ticker/btc/',
> function(data){
> var symbol = (data[0].symbol)
> })
Once I have it I can place it in a div.
However when I use cryptocompare API I don't get anything back
https://min-api.cryptocompare.com/data/coin/generalinfo?fsyms=BTC,&tsym=USD
$.getJSON('https://min-api.cryptocompare.com/data/coin/generalinfo?fsyms=BTC&tsym=USD', function(data){
var symbol = (data[0].Internal)
});
This is the response -
{
"Message": "Success",
"Type": 100,
"Data": [
{
"CoinInfo": {
"Id": "1182",
"Name": "BTC",
"FullName": "Bitcoin",
"Internal": "BTC",
"ImageUrl": "/media/19633/btc.png",
"Url": "/coins/btc/overview",
"Algorithm": "SHA256",
"ProofType": "PoW",
"NetHashesPerSecond": 27483320229.3688,
"BlockNumber": 518932,
"BlockTime": 600,
"BlockReward": 12.5,
"Type": 1,
"DocumentType": "Webpagecoinp"
},
"ConversionInfo": {
"Conversion": "direct",
"ConversionSymbol": "",
"CurrencyFrom": "BTC",
"CurrencyTo": "USD",
"Market": "CCCAGG",
"Supply": 16986575,
"TotalVolume24H": 380849.0498955779,
"SubBase": "5~",
"SubsNeeded": [
"5~CCCAGG~BTC~USD"
],
"RAW": [
"5~CCCAGG~BTC~USD~4~8875.23~1524460635~0.00477012~42.152119404000004~231254719~10820.885574747872~96327075.76938197~66326.58563159907~593473019.8524572~8823.46~8917.05~8804.2~8864.31~9065~8780.91~Bitfinex~7ffe9"
]
}
}
]
}
Why is the second piece of code not working? Please help!
The second API is returning an object (in JSON format), not an array - see how the first character is { and how it has keys and values? You need to access the appropriate property to get the value you want. [0] notation indicates you're trying to access the first element of the array, but the outer object is not an array in this situation.
$.getJSON('https://min-api.cryptocompare.com/data/coin/generalinfo?fsyms=BTC&tsym=USD',
function(data){
var symbol = data.Data[0].CoinInfo.Internal;
});
In both the cases, we are getting data in different form. So, To get the 'BTC' in variable .
for 1st case -> symbol = data[0] ['symbol']
for 2nd case -> symbol = data['Data'][0]['CoinInfo']['Internal']
one is an [array of JSON] while other is an [object having key 'Data' with array value].
Related
[
{
"id": "628ba44f5a6de600071d16fa",
"#baseType": "LogicalResource",
"isBundle": false,
"isMNP": false,
"businessType": [],
"category": [
{
"id": "628ba3ef5a6de600071d165f",
"name": "Starterpack2",
"description": "Starterpack2",
"code": "RC17",
"version": 2
}}]
now i need to check and print the JSON Object inside the JSON Array if category is present then it should print and in future if category is changed according to that if we pass parameter the output should print we don't hard code the code
i have tried by using key values it is coming but if the key value changes it is not printing the object
EX:-
[
{
"id": "628ba44f5a6de600071d16fa",
"#baseType": "LogicalResource",
"isBundle": false,
"isMNP": false,
"businessType": [],
"category": [
{
"id": "628ba3ef5a6de600071d165f",
"name": "Starterpack2",
"description": "Starterpack2",
"code": "RC17",
"version": 2
}}]
in the above code i have printed category object but if category changed to categories it is not printing so i want a code which can read the code and based on parameters user giving it should be print the output
Try this.
For Example:
let a = [{"id": "628ba44f5a6de600071d16fa","category": [
{
"id": "628ba3ef5a6de600071d165f",
"name": "Starterpack2",
"description": "Starterpack2",
"code": "RC17",
"version": 2
}]}]
function print (values){return (a[0][`${values}`])}
//now just pass any name like "category" or in future "categories"
print("category") //this will retrun the array.
Now modify with your requirements.
It seems you want to get the value of the key(that can be parameterized).
const jsonArray = [
{
"id": "628ba44f5a6de600071d16fa",
"#baseType": "LogicalResource",
"isBundle": false,
"isMNP": false,
"businessType": [],
"category": [
{
"id": "628ba3ef5a6de600071d165f",
"name": "Starterpack2",
"description": "Starterpack2",
"code": "RC17",
"version": 2
}
]
}
];
const parameter = "category";
const result = jsonArray.find(({ [parameter]: value }) => value);
if (result) {
console.log(result);
} else {
console.log(`No object found with ${parameter}`);
}
If this is not what you are looking for, then please add your code snippet for better understanding.
I am attempting to create a JSON Object from an array to pass into a Microsoft product. The format in which the JSON object is accepted is shown beneath (content-type: "application/json"):
{
"value": [
{
"activityGroupNames": [],
"confidence": 0,
"description": "This is a canary indicator for demo purpose. Take no action on any observables set in this indicator.",
"expirationDateTime": "2019-03-01T21:44:03.1668987+00:00",
"externalId": "Test--8586509942423126760MS164-0",
"fileHashType": "sha256",
"fileHashValue": "b555c45c5b1b01304217e72118d6ca1b14b7013644a078273cea27bbdc1cf9d6",
"killChain": [],
"malwareFamilyNames": [],
"severity": 0,
"tags": [],
"targetProduct": "Azure Sentinel",
"threatType": "WatchList",
"tlpLevel": "green",
},
{
"activityGroupNames": [],
"confidence": 0,
"description": "This is a canary indicator for demo purpose. Take no action on any observables set in this indicator.",
"expirationDateTime": "2019-03-01T21:44:03.1748779+00:00",
"externalId": "Test--8586509942423126760MS164-1",
"fileHashType": "sha256",
"fileHashValue": "1796b433950990b28d6a22456c9d2b58ced1bdfcdf5f16f7e39d6b9bdca4213b",
"killChain": [],
"malwareFamilyNames": [],
"severity": 0,
"tags": [],
"targetProduct": "Azure Sentinel",
"threatType": "WatchList",
"tlpLevel": "green",
}
]
}
I making use of an inline code script in Microsoft automate that performs the following in JavaScript:
var threat = workflowContext.actions.Compose.outputs;
var value = Object.values(threat);
return value;
The workflowContext.actions.Compose.outputs line pulls an array consisting of objects shown in the following snippet:
[{"id": "1", "activityGroupNames": "test2"}, {"id": "2", "activityGroupNames": "test3"}, {"id": "3", "activityGroupNames": "test4"}]
This is my output:
{
"body": [
{
"id": "1",
"action": "alert",
"activityGroupNames": "test2"
},
{
"id": "2",
"action": "alert",
"activityGroupNames": "test3"
},
{
"id": "3",
"action": "alert",
"activityGroupNames": "test2"
}
]
}
it is pretty much identical to the format described my Microsoft shown in the first snippet. (https://learn.microsoft.com/en-us/graph/api/tiindicator-submittiindicators?view=graph-rest-beta&tabs=http) at the bottom.
I am unsure as to how I can change the key name from "body" to "value" and think maybe this will resolve my issue. Either way, I'd appreciate any other help on the matter, if any more context is required, please ask.
EDIT: The image beneath shows that the returned return value; is in fact being used as the input for a POST request to the Microsoft graph API
I have a huge static JSON file that contains all champions in a certain game and some information about them. Currently, I need to figure out how to find the champion object whose "key" property is 266. Sadly I'm having some difficulty figuring out how to get that object. I assume I have to loop through the objects, however, usually when I loop through something, it's an array but this is not the case.
I've put a simplified example of the json structure below. I have an integer 266 and now I need to somehow access the object with "key": "266" which would be Aatrox. Any clues on how would I do that?
"data": {
"Aatrox": {
"version": "8.19.1",
"id": "Aatrox",
"key": "266",
"name": "Aatrox",
"title": "the Darkin Blade"
},
"Ahri": {
"version": "8.19.1",
"id": "Ahri",
"key": "103",
"name": "Ahri",
"title": "the Nine-Tailed Fox"
}
}
You can use find
Get the entries from data key using Object.entries
Find value whose key property is equal to our desired key using find
let obj = {"data": {"Aatrox": {"version": "8.19.1","id": "Aatrox","key": "266","name": "Aatrox","title": "the Darkin Blade"},"Ahri": {"version": "8.19.1","id": "Ahri","key": "103","name": "Ahri","title": "the Nine-Tailed Fox"}}}
let findByKey = (matchKey) => Object.entries(obj.data).find(([key,value]) => value.key === matchKey)
console.log(findByKey('266'))
Here's a generic function you can use to search for any key and value:
const obj = {"data": {"Aatrox": {"version": "8.19.1","id": "Aatrox","key": "266","name": "Aatrox","title": "the Darkin Blade"},"Ahri": {"version": "8.19.1","id": "Ahri","key": "103","name": "Ahri","title": "the Nine-Tailed Fox"}}}
const searchKeyValue = {key:"key", value:"266"}
const search = data => skv => Object.entries(data).filter(([key,value])=>value[skv.key]===skv.value)
console.log(search(obj.data)(searchKeyValue))
So you can find via e.g. searchKeyValue = {key:"id", value:"Ahri"} or whatever you like.
You could also use JSONPath i.e.
$..data[?(#.key==266)]
Assuming :
{"data": {
"Aatrox": {
"version": "8.19.1",
"id": "Aatrox",
"key": "266",
"name": "Aatrox",
"title": "the Darkin Blade"
},
"Ahri": {
"version": "8.19.1",
"id": "Ahri",
"key": "103",
"name": "Ahri",
"title": "the Nine-Tailed Fox"
}
}
}
I am working with facebook JS SDK which returns user's information in JSON format. I know how to get the response like response.email which returns email address. But how to get an element from a nested array object? Example: user's education history may contain multiple arrays and each array will have an element such as "name" of "school". I want to get the element from the last array of an object.
This is a sample JSON I got:-
"education": [
{
"school": {
"id": "162285817180560",
"name": "Jhenaidah** School"
},
"type": "H**hool",
"year": {
"id": "14404**5610606",
"name": "2011"
},
"id": "855**14449421"
},
{
"concentration": [
{
"id": "15158**968",
"name": "Sof**ering"
},
{
"id": "20179020**7859",
"name": "Dig**ty"
}
],
"school": {
"id": "10827**27428",
"name": "Univer**g"
},
"type": "College",
"id": "9885**826013"
},
{
"concentration": [
{
"id": "108196**810",
"name": "Science"
}
],
"school": {
"id": "2772**996993",
"name": "some COLLEGE NAME I WANT TO GET"
},
"type": "College",
"year": {
"id": "1388*****",
"name": "2013"
},
"id": "8811215**16"
}]
Let's say I want to get "name": "some COLLEGE NAME I WANT TO GET" from the last array. How to do that with Javascript? I hope I could explain my problem. Thank you
Here is a JsFiddle Example
var json = '{}' // your data;
// convert to javascript object:
var obj = JSON.parse(json);
// get last item in array:
var last = obj.education[obj.education.length - 1].school.name;
// result: some COLLEGE NAME I WANT TO GET
If your json above was saved to an object called json, you could access the school name "some COLLEGE NAME I WANT TO GET" with the following:
json.education[2].school.name
If you know where that element is, then you can just select it as already mentioned by calling
var obj = FACEBOOK_ACTION;
obj.education[2].school.name
If you want to select specifically the last element, then use something like this:
obj.education[ obj.education.length - 1 ].scool.name
Try this,
if (myData.hasOwnProperty('merchant_id')) {
// do something here
}
where JSON myData is:
{
amount: "10.00",
email: "someone#example.com",
merchant_id: "123",
mobile_no: "9874563210",
order_id: "123456",
passkey: "1234"
}
This is a simple example for your understanding. In your scenario of nested objects, loop over your JSON data and use hasOwnProperty to check if key name exists.
I've tried 100 different things, and spend days looking through Google and Stackoverflow, but I can't find a solution to this problem. Everything I call after the body of this API response returns undefined!
The response from Facebook SDK looks like this:
[
{
"body": "[
"data": [
{
"name": "Larry Syid Wright",
"administrator": false,
"id": "xxx"
}, {
"name": "Melissa Long Jackson",
"administrator": false,
"id": "xxx"
}, {
"name": "Charlotte Masson",
"administrator": false,
"id": "xxx"
}
],
"paging": {
"next": "url"
}
]"
},{
"body": "{
"data": [
{
"id": "xxx_xxx",
"message": "In honor of Halloween, how many of you have your own ghost stories? Who believes in ghosts and who doesn't?",
"type": "status",
"created_time": "2014-10-31T20:02:01+0000",
"updated_time": "2014-11-01T02:52:51+0000",
"likes": {
"data": [
{
"id": "xxx",
"name": "Joe HerBatman Owenby Jr."
}
],
}
"paging": {
"cursors":
{
"after": "xxx",
"before": "xxx"
}
}
}
},{
"id": "xxx_xxx",
"from": {
"id": "xxx",
"name": "Jessica Starling"
},
"message": "Watching the "Campaign" and I can't help but notice what a fantastic job they did (Will ferrell and all) with that North Carolina accent! Ya'll know we sound different than other southern states ;)",
"type": "status",
"created_time": "2014-11-01T02:36:21+0000",
"updated_time": "2014-11-01T02:36:21+0000",
"likes": {
"data": [
{
"id": "xxx",
"name": "Scott Williams"n
}
]
}
}
],
"paging": {
"previous": "xxx",
"next": "xxx"
}
}"
}
]
This response is from a batch call. If I call them separately, I can easily iterate through the responses, and get everything from them. When I call them in the batch though, I can't get past "body", and I need to use a batch call.
console.log(response[0].body); will return the object inside the body of the first part of the response, but console.log(response[0].body.data); returns undefined. I just don't get it. This should be simple but it's like there's a lock on the door and I don't have the right key.
I normally have no issue iterating through objects, so I don't need a generalized answer. I need help seeing whatever it is here that I don't see. Why does the console show undefined when I call anything after the body, and what do I need to be doing to get any of these values?
That JSON contains nested JSON. body seems to be a string. Use
var body = JSON.parse(response[0].body);
The values from the body are just strings.which are embedded as json.So firstly you would need to parse them using JSON.parse.
The code would be like
var body = JSON.parse(response[0].body);