How to extract data from an API in json - json

I am trying to create simple code to fetch data from an api which contains the price of bitcoin and store it. I am new to json and have tried everything I could think of. Here is the code.
await getRemoteData('https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd')
.then((response) => {
const data = JSON.parse(response);
const price = ${data.value};
})
Thanks in advance!

JSON looks something like {"foo": "bar"} so it's basically collection of strings and values. in order to get value from some json say value of key "price", in js you need to parse JSON string to JSON Object first (which you already did by const data = JSON.parse(response);) and get the price by:-
const price = data.price // assuming that the key is "price"
if you want some other value with different key, say key is "foo" then you can fetch the value by let valueOfFoo = data.foo

Related

typescript - load json from url and get access to array of json objects

I just can't find a working solution and implement in my format.
There is a JSON file which is returned to me by URL. Its format is:
{"success":true,
"data":[
{
"loadTimestamp":"2022-07-20T15:12:35.097Z",
"seqNum":"9480969",
"price":"45.7",
"quantity":"0.2",
"makerClientOrderId":"1658329838469",
"takerClientOrderId":"1658329934701"
},
{
"loadTimestamp":"2022-07-20T14:49:11.446Z",
"seqNum":"9480410",
"price":"46",
"quantity":"0.1",
"makerClientOrderId":"1658328403394",
"takerClientOrderId":"0"
}]
}
Due to the fact that it is returned via the URL, it is not possible to directly use the object, for example:
myobj['data']['price']
I have either a string of data that I can convert using JSON.parse() or an object right away.
But for some reason I can't use it directly.
As far as I understand, this is a JSON file inside which is an array of JSON data.
My goal is to display all the data from the array, while taking for example 2 values: price, quantity
How can I access the values that I want to get?
Ok I find, what I was looking for.
I return result not in json, but in text response.text()
After I did this, I create a new constant called res and put in it JSON.parse(data)
const url = 'https://myurl.com/'+pub_key
const response = await fetch(url)
let data = ''
if (response.ok) { data = await response.text() } else { console.log("Error HTTP: " + response.status) }
const res = JSON.parse(data)
After all this manipulations I can use my data with 2 ways:
console.log(res["data"][0]["price"])
console.log(res.data[0].price)
Or I can make a cocktail from it, by using my favorite blender :)))
if(res.success==true){
for(let item in res.data){
console.log(res.data[item].price,res.data[item].quantity)
}
}

Typescript JSON How do I read JSON using hierarchical key like "appInsights:instrumentationKey"

Given the below JSON, I should be able to read the JSON using hierarchical key path such as "appInsights:instrumentationKey". How can i do this in an angular project?
{
"appInsights": {
"instrumentationKey": "<dev-guid-here>"
}
},
Is this what you are looking for ?
const obj = JSON.parse('your json');
const val1 = obj.appInsights.instrumentationKey;
const val2 = obj['appInsights'].instrumentationKey;
UPDATE: Will has fair point. If your JSON data doesnt contain user input e.g won't contain anything harmful that will execute in browser then
const val = eval('obj.' + keyPath.replace(/:/g, '.'));
or if you use Lodash: get
Something along these lines perhaps:
getJsonProperty(jsonObj, keyPath: string) {
const keys: string[] = keyPath.split(':');
return jsonObj[keys[0]][keys[1]];
}
If you don't know how many levels the object can have, you could write a switch statement with cases for each accepted length of the keys Array. Obviously that means hard-coding each case (and a fixed maximum number of possible levels), unless there's some other way of using string literals I'm forgetting.

Find a word in a steam json and print

I am trying to print the number after quantity in the following JSON:
app_data : {
quantity: 1,
...
...
}
This is the link where I am trying to print
chrome_options = Options()
chrome_options.add_argument("--headless")
driver = webdriver.Chrome(executable_path=os.path.abspath("chromedriver"), options=chrome_options)
inv = "https://steamcommunity.com/profiles/76561198404652782/inventory/json/440/2"
with urllib.request.urlopen(inv) as url:
data = json.loads(url.read().decode())
result = data.find('quantity')
print(data, result)
print(data)
Also tried .find() but no success
json.loads() returns a dictionary, and a dictionary does not have a find() method on it. Also, what the request returns is a nested dictionary, so a direct key lookup won't work. You may have to try something like what's been suggested in these earlier posts.
Find all occurrences of a key in nested python dictionaries and lists
How can I search for specific keys in this nested dictionary in Python?
You are searching for a key, So just use a condition for it..
if 'quantity' in data:
print data['quantity']

want read a specific item from data() method in firestore

snapshot.forEach(doc => {
console.log("ID: "+doc.id, '=>', "Doc DATA: "+JSON.stringify(doc.data()));
});
I want to read only 1 item from doc.data() and that is an array of strings called ("supportedCurrencies").
How do i read? I'm new to firestore and TS so any help much appreciated.
Thanks!
When you call doc.data() you get a plain JavaScript object whose properties are each of the fields in the document:
const data = doc.data();
If you want one of those fields, just access it by name as a property of that object:
const supportedCurrencies = data.supportedCurrencies;
If it's an array, then you can treat it just like any other JavaScript array object.

Extract key/value pairs from $http response in angularjs

I have a rest call to a server which returns me something that looks like this:
response.searchResult = ["{\"key1\":\"value1\",
\"key2\":\"value2\",
\"key3\":\"value3\"}"]
How can I extract all key-value pairs into a json array? Or at the very least, how can I search for the value associated with a specific key, lets say "key2" from the example?
Just run json.parse on the array entry:
response.searchResult = ["{\"key1\":\"value1\",\"key2\":\"value2\",\"key3\":\"value3\"}"];
var jsonResult = JSON.parse(response.searchResult[0]);
console.log(jsonResult);