How to display specific information from JSON API? - json

How can i display the value of a specific variable stored in an JSON API array?
For e.g. how could i display the current Bitcoin price in USD in a specific wordpress post using coinmarketcaps JSON API (https://api.coinmarketcap.com/v1/ticker/bitcoin/)?
The API gives me the following output:
[
{
"id": "bitcoin",
"name": "Bitcoin",
"symbol": "BTC",
"rank": "1",
"price_usd": "3351.98",
"price_btc": "1.0",
"24h_volume_usd": "1455740000.0",
"market_cap_usd": "55289274334.0",
"available_supply": "16494512.0",
"total_supply": "16494512.0",
"percent_change_1h": "0.55",
"percent_change_24h": "3.45",
"percent_change_7d": "17.52",
"last_updated": "1502145551"
}
]
I only need to display the value of "price_usd" tho.
I've tried to do it this way, but it didn't work:
<script>
var btcPrice;
function UpdateBtcPrice(){
$.ajax({
type: "GET",
url: "https://api.coinmarketcap.com/v1/ticker/bitcoin/",
dataType: "json",
success: function(result){
btcPrice = result[0].price_usd;
},
error: function(err){
console.log(err);
}
});
}
</script>
Any help would be much appreciated!

You need to call the function to execute the request:
var btcPrice;
function UpdateBtcPrice(){
$.ajax({
type: "GET",
url: "https://api.coinmarketcap.com/v1/ticker/bitcoin/",
dataType: "json",
success: function(result){
btcPrice = result[0].price_usd;
},
error: function(err){
console.log(err);
}
});
}
UpdateBtcPrice();

You can try this code
<?php
//get data with api call
$response = file_get_contents('https://api.coinmarketcap.com/v1/ticker/bitcoin/');
$response = json_decode($response);
echo $response[0]->price_usd;//print the value
?>

Related

Not a valid json request, from DolphinDB JSON API

I'm trying the JSON API provided by DolphinDB, following this tutorial.
And I tried the code snippet like this:
var code = "1+2";
code = encodeURIComponent(code);
paramJson = {
"sessionID": "942605602",
"functionName": "executeCode",
"params": [{
"name": "script",
"form": "scalar",
"type": "string",
"value": code
}]
}
var option = {
url: "http://localhost:9920",
async: true,
data: paramJson,
type: "POST",
dataType: "json",
success: function (data) {
var resultJson = data;
console.log(data);
}
}
$.ajax(option);
Here is the log I got from chrome:
{sessionID: "800870454", userId: "", resultCode: "1", msg: "not a valid json request [sessionID=942605602&func…type%5D=string&params%5B0%5D%5Bvalue%5D=1%252B2].", object: Array(0)}msg: "not a valid json request [sessionID=942605602&functionName=executeCode&params%5B0%5D%5Bname%5D=script&params%5B0%5D%5Bform%5D=scalar&params%5B0%5D%5Btype%5D=string&params%5B0%5D%5Bvalue%5D=1%252B2]."object: []resultCode: "1"sessionID: "800870454"userId: ""__proto__: Object
It report not a valid json request, but I don't know what's wrong with my request.
You can try serializing JSON objects before sending requests
data = JSON.stringify(paramJson)

Trying to Retrieve Line Status from TfL's API (JSON)

I'm messing around with AJAX/JSON for a bit of practice, and I'm attempting to retrieve live data from TfL's (Transport For London) API pertaining to train line statuses.
Here is a snippet of the JSON data I am working with:
[
{
"$type": "Tfl.Api.Presentation.Entities.Line, Tfl.Api.Presentation.Entities",
"id": "bakerloo",
"name": "Bakerloo",
"modeName": "tube",
"disruptions": [],
"created": "2018-10-05T11:35:58.573Z",
"modified": "2018-10-05T11:35:58.573Z",
"lineStatuses": [
{
"$type": "Tfl.Api.Presentation.Entities.LineStatus, Tfl.Api.Presentation.Entities",
"id": 0,
"statusSeverity": 10,
"statusSeverityDescription": "Good Service",
"created": "0001-01-01T00:00:00",
"validityPeriods": []
}
],
I am trying to retrieve the name of the of the line (called "name" in JSON data) and the current status (called "statusSeverityDescription" in the data"). The code below can retrieve the name, but I have no idea how to retrieve statusSeverityDescription as it appears to be held within {}'s within an array.
$.ajax({
type: 'GET',
url: 'https://api.tfl.gov.uk/line/mode/tube/status',
dataType: 'json',
success: function(data) {
$.each(data, function(key, value){
var line = value.name;
var status = value.lineStatuses[0];
$("#content").append("<tr><td>" + line + "</td>" + "<td>" + status + "</td></tr>");
});
}
})
Any help would be much appreciated.
Thanks.
You already have the status object, so you just need to access status.statusSeverityDescription.

Ajax post request to google NLP

Im trying to do a post request to GCP Natural Language for sentiment analysis.
When I try the data format on the code explorer on google it works fine but when I run it on a html page I get an error that reads
{
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name \"document[type]\": Cannot bind query parameter. Field 'document[type]' could not be found in request message.\nInvalid JSON payload received. Unknown name \"document[content]\": Cannot bind query parameter. Field 'document[content]' could not be found in request message.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [
{
"description": "Invalid JSON payload received. Unknown name \"document[type]\": Cannot bind query parameter. Field 'document[type]' could not be found in request message."
},
{
"description": "Invalid JSON payload received. Unknown name \"document[content]\": Cannot bind query parameter. Field 'document[content]' could not be found in request message."
}
]
}
]
}
}
My code is:
<!DOCTYPE html>
<html>
<body>
<h1> Testing sentiment Analysis </h1>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var APIKEY = "AN API KEY";
$.ajax({
type : "POST",
url : "https://language.googleapis.com/v1/documents:analyzeSentiment?key="+APIKEY,
data : {
"document": {
"type": "PLAIN_TEXT",
"content": "Hello I am great"
},
"encodingType": "UTF8",
},
success: function(res) {
console.log(res);
alert(res['message']);
},
error: function(res) {
console.log(res['message']);
alert(res);
},
});
</script>
</body>
</html>
UPDATE:
A colleague has pointed me to the MISTAKE I was making. We have to use JSON.stringify() in order to send the request. The code should be like this:
$.ajax({
type : "POST",
url : "https://language.googleapis.com/v1/documents:analyzeEntitySentiment?key=YOUR-API-KEY",
contentType : "application/json; charset=utf-8",
data :
JSON.stringify({
"document": {
"type": "PLAIN_TEXT",
"language": "en",
"content": "Hola Victor"
},
"encodingType": "UTF8"}),
success : function(_result){
if (_result) {
alert('SUCCESS');
} else {
alert('ERROR');
}
},
error : function(_result){
}
});
I have tested it and it works.

google qpx query in Google script

i'm tryng to request a (simple) flight-query trough google flight service via Apps Script
this is my code
function myFunction() {
var api_key = "XXXXXXXXXXXXXXX";
var url2= "https://www.googleapis.com/qpxExpress/v1/trips/search?key=" + api_key;
var param2 ={
"method" : "POST",
"contentType":"application/json",
"headers" : {"Content-Type": "application/json"
},
"request": {"passengers": {"adultCount": 1},
"slice": [{"origin": "BOS","destination": "LAX","date": "2015-03-01"}]
},
muteHttpExceptions : true
};
try {
var response = UrlFetchApp.fetch(url2,param2);
Logger.log(response)
} catch (e) {
Logger.log(e)
}
}
this request send me error code
"error": {"errors": [{
"domain": "global",
"reason": "badRequest",
"message": "Invalid inputs: received empty request."
}
],
"code": 400,
"message": "Invalid inputs: received empty request."
}
The qpx Api is loaded in my developer console....anyone has any idea?
thanks in advance
Two things, the body of the request must be specified with the "payload" property, not "request", and you must actually convert your Javascript Object to a JSON string before posting it. (You also don't need the "headers" property, "contentType" will suffice, but I don't think it hurts anything)
var param2 ={
"method" : "post",
"contentType":"application/json",
"payload": JSON.stringify({"passengers": {"adultCount": 1},
"slice": [{"origin": "BOS",
"destination": "LAX",
"date": "2015-03-01"
}]
}
),
muteHttpExceptions : true
};
It's all documented here: https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app#fetch(String,Object)
However, the need to JSON.stringify() usually throws people off, if you pass a Javascript Object directly in the payload it is posted as form-encoded key/value pairs.
thanks very much...you put me in the right direction!
this is the right syntax:
var param2 ={
"method" : "post",
"contentType":"application/json",
"payload": JSON.stringify
(
{"request":
{"passengers": {"adultCount": 1},
"slice": [{"origin": "BOS",
"destination": "LAX",
"date": "2015-03-01"
}]
}
}
),
muteHttpExceptions : true
};

I try to generate output the json string return from php but i cant do it

tthe following is my json string return from php and suggest me how i can get value from following json string.
[
{
"picid": "13",
"itemcode": "P-0000001",
"filename": "-1970-01-011.jpg",
"primarystatus": "active"
},
{
"picid": "16",
"itemcode": "P-0000001",
"filename": "dateArray1.jpg",
"primarystatus": "active"
},
{
"picid": "18",
"itemcode": "P-0000001",
"filename": "dateArray3.jpg",
"primarystatus": "active"
},
{
"picid": "19",
"itemcode": "P-0000001",
"filename": "dateArray4.jpg",
"primarystatus": "active"
}
]
//php
function returnALLPic()
{
if(isset($_POST['id']))
{
$data= $this->m_phone->getAllPictureInformation($_POST["id"]);
$ss= json_encode($data);
echo $ss;
}
}
//jquery
$.ajax({
type: 'POST',
url: 'http://localhost/tt/index.php/ad_access/c_r/returnALLPic',
data: 'id='+ei,
success: function(msg)
{
// console.log(JSONObject); // Dump all data of the Object in the console
$('#model').html(msg[0].itemcode)
}
});
You can parse json using following code.
var json = $.parseJSON(j);
$(json).each(function(i,val){
$.each(val,function(k,v){
console.log(k+" : "+ v);
});
});
You can do this in PHP as well.
Read this using
$data = file_get_contents('Your_URL')
and then use following function to parse it
$phpArray = json_decode($data);
You can do what ever you want do with that
If you need to output in php, use json_decode()
then get what you want from the loop
$sss= json_decode($data)