how can I push the data I get from https://somelink.com into a variable that I can display?
--> for example, the response is in this format {"ABC":1435.21}
e.g. I want to display "The value of ABC is 1435.21"
The response you are getting is JSON data, you can use that data like this
$.get( "https://somelink.com", function( data ) {
//Get first key of JSON object as String
let name = Object.keys(data)[0];
//Get value by key name
let value = data[name];
//Output
console.log("The value of "+name+" is "+value);
alert("The value of "+name+" is "+value);
}, "json" );
The last parameter of $.get() tells that we will be receiving JSON formatted data from server.
Related
I'm receiving some error response in ajax error function;
$.ajax(Request).error(function (Response) {
var content = JSON.stringify(Response.responseText);
var obj = JSON.parse(content);
console.log("Response.responseText:",Response.responseText);
console.log("Response.responseText.Message:", Response.responseText.Message);
console.log("Response.responseText[Message]:", Response.responseText["Message"]);
console.log("content:", content);
console.log("content.Message:", content.Message);
console.log("content[Message]:", content["Message"]);
console.log("obj:", obj);
console.log("obj.message:", obj.Message);
console.log("obj[Message]:", obj["Message"]);
});
Here are outputs of console.log :
I need to access Message but none of them create access to its value. How can I access Message?
Main Question
why all of them are undefined?
How can I access Message?
Solution
var parsed= JSON.parse(startpaymentResponse.responseText);
console.log("parsed:", parsed);
console.log("parsed.Message:", parsed.Message);
console.log("parsed[Message]:", parsed["Message"]);
Meanwhile when I copy Response.responseText to JSON Deserialize Online, everything is fine.
Response.responseText: {"Message":"The request is invalid.","ModelState":{"model.Amount":["The field Amount must be a string or array type with a minimum length of '4'."],"model.TotalAmount":["The field TotalAmount must be a string or array type with a minimum length of '4'."]}}
Okay, so the problem is that Response.responseText is already a string. You don't need to do JSON.stringify(Response.responseText). Please directly, parse it to JSON and then use the object:
$.ajax(Request).error(function (Response) {
var obj = JSON.parse(Response.responseText);
console.log("obj.Message", obj.Message);
});
I am new to JSON and concepts. I want to extract the data from an API which i have mentioned below, basically i want to extract several details from this API about an Stock. The problem here is, after parsing the URL i dont know how to extract the value for each variablle.
I want to extract the data into an GoogleSheet.
the output of the below function shows, like this
[20-12-10 20:45:15:806 CET] [{symbol=JMIA, price=37.0497, volume=1.317713E7}]
The output i wanted is that:
JMIA
37.0497
1.317713E7
Code :
function CurrentPrice() {
var url = 'https://financialmodelingprep.com/api/v3/quote-short/JMIA?
apikey=7c2f5bcb573b33050c1aad41a54919';
var response = UrlFetchApp.fetch(url);
// convert json string to json object
var jsonSignal = JSON.parse(response);
Logger.log(jsonSignal);
}
I suggest you read this "Working with Objects" article.
The response is wrapped in brackets [] meaning it's an array. I assume you're only expecting one response, so you can grab that first element using jsonSignal[0], which will give you an object.
To get an object property, you have to specify the property name using either dot- or bracket-notation. (I'll use dot-notation.)
const jsonSignal = [{symbol:'JMIA', price:37.0497, volume:1.317713E7}];
console.log(jsonSignal[0].symbol); // 'JMIA'
function CurrentPrice() {
const url = 'https://financialmodelingprep.com/api/v3/quote-short/JMIA?apikey=API_KEY';
const response = UrlFetchApp.fetch(url);
// Convert HTTPResponse
// Use the first element in the response array
const signal = JSON.parse(response)[0];
console.log(signal.symbol); // 'JMIA'
console.log(signal.price); // 37.0497
console.log(signal.volume); // 1.317713E7
}
Try like this :
var json = response.getContentText();
var data = JSON.parse(json);
Logger.log(data);
I read that there : https://developers.google.com/apps-script/guides/services/external
Regards
How can I extract value from response?
Output of alert is [{"maturitydays":"120"}]
I only want value!!
$("#selectCrop").change(function(){ //this ajax will bring default configured crop data
var cropid = $("#selectCrop option:selected").val();
var url = "<?php echo base_url();?>index.php/user/cropConfig/getData";
$.ajax({
data : {'cropid':cropid},
type : 'post',
url : url,
success :function(response) {
alert(response);
}
})
});
It appears your response is inside an array due to the square brackets, this means you need to get the value through:
response[0]['maturitydays']
So your code will look like:
$("#selectCrop").change(function(){ //this ajax will bring default configured crop data
var cropid = $("#selectCrop option:selected").val();
var url = "<?php echo base_url();?>index.php/user/cropConfig/getData";
$.ajax({
data : {'cropid':cropid},
type : 'post',
url : url,
success :function(response) {
alert(response[0]['maturitydays']);
}
})
});
It's json.
Use json_decode to make it array then grab the value from the array (if you must).
$array = json_decode('{"maturitydays":"120"}',true);
$value=$array["maturitydays"];
Echo $value;
https://3v4l.org/Uc51m
The data that you get as response is a JSON array with a number of JSON objects. JSON (JavaScript object notation) can be used as a JavaScript object right away (as long as its not in string form, in which case it has to be parsed with JSON.parse).
When you receive the response you can access it as you would with a normal JavaScript array (in case you are sure its ALWAYS only 1 object, you can select the first index right away):
let obj = response[0];
When you got the object, just access the value you want as you would with a normal JavaScript object:
let val = obj.maturitydays;
How can I get the second data of this JSON - I am beta. in jQuery?
{"alpha":["I am alpha"],"beta":["I am beta."]}
You can go through array and search for keys what you want... but dont forget to encode json string
$data= json.encode($input)
foreach($data as $key => $val)
{
if($key=='beta')
do something
else
do something else
}
I hope it help you.
Assuming that your json is in a string variable as:
var data = '{"alpha":["I am alpha"],"beta":["I am beta."]}';
You can parse the string as a json object and then access the content like this:
json = JSON.parse(data);
//or if you strictly need to use jQuery
json = $.parseJSON(data);
alert(json.alpha[0]);
alert(json.beta[0]);
If you don't know which is the json content you can iterate through json object like this:
for (var key in json) {
if (json.hasOwnProperty(key)) {
alert(key + " -> " + json[key]);
}
}
Finally I come up with this
Step 1: Json parsed,
Step 2 : Declared in another string
Step 3 : And then looped inside each entry
obj=JSON.parse(data);
var error_string='';
$.each(obj, function(entry) {
error_string+=obj[entry]+'<br/>';
});
$('#stage').html(error_string);
}
And then i got the values that is inside, Now i can able to get the values inside the object even for n numbers.
I am into some weird situation where JSON response is-
{"Id":1,"service_name":"asdf","service_charge":11.32,"service_type":null,"service_comission":14.65,"service_desc":"","after_service_charge":23.55,"service_duration":60,"after_service_comission":11.22,"service_frequency":58,"tax_rate":15}
Condition-
In my form- #form-service-values I have input field of same name as it comes in response. Now I wanted to fetch value from JSON where data name matches.
For ex-
data.service_name logs me with value asdf
But Now here It is coming to me when name is dynamic of input fields as-
[object Object].service_name
Here Is how I am handling it in ajax-
function getDescService(Idservice) {
$.ajax({
url: '/Service/GetServiceDescriptions/',
type: 'post',
data: { Id: Idservice },
success: function (data) {
$('#form-service-values input[type="text"]').each(function () {
var name = $(this).attr('name');
$(this).val(data + "." + name);
})
}
});
}
I am trying to get this JSON response in a form where name of inputs are same as it comes in JSON response.
I just want to access JSON data fields.
How do I try on it?
In javascript, an object can be access like that data.name, where name is the key, or like that data["name"]
So you should do this
$(this).val(data[name]);
Instead of this
$(this).val(data + "." + name);
The first one is retrieving the value stored at the key name in the object data, while the second one is only writing text.