How to get the values from the Json using Jquery - json

Hi I'm new to Jquery and i don't know how to use json data. I have a Json which is coming as a response. My success function is
success: function(resp)
{
var x = JSON.stringify(resp);
alert(x);
}
alert is having following JSON
{"xyz":{"abc":[{"action":"fail","result":"xxx"},{"action":"pass","resut":"yyy"}]}}
I want action value alone. How can i get this value from x variable and how can i utilize this value in HTML. Thanks in advance.

When you use JSON.stringify() you are turning it into a string, you want it as an object to access the data. Try this:
success: function(resp) {
alert(resp.xyz.abc[0].action);
var x = resp.xyz.abc[0].action // to use the value in html later on
}
If it is returned as a string (I can't tell at this point), you can turn it into an object (as long as it is valid JSON) by using $.parseJSON()

success: function(resp)
{
var x = $.parseJSON(resp);
var xyz = x.xyz;
var pass = x.xyz.abc[1].action;
}
or you can loop though each of the array by $.each
success: function(resp)
{
var x = $.parseJSON(resp);
$.each(x.xyz.abc, function(index, element){
alert('action:' + element.action + ', result:' + element.resut)
});
}

i think, and don't take it personally,that your JSON object is not well organized as an object to get and to have. Action,from my perspective is either fail or success, and reading it, as you saw in the above good answer, will give you exactly what you want.
What's the point in getting a JSON with data structured like you did, with 2 possible answers encoded in it, when there is only one available (either success or fail).

Related

I have a url getting XY in json from php, The result is like [{"status":"ok","data":{"latitude":0.625,"longitude":0.855}}]. End result is "undefined"

I have a url getting XY in json from php, The result is like [{"status":"ok","data":{"latitude":0.625,"longitude":0.855}}]. End result is "undefined"
<body>
<div class="GPSData"></div>
<script>
$.getJSON('http://api.alqimma.com.sa/index.php?key=??&type=live&vehicle=1865',
function (json) {
var mydata = `<b> ${json.longitude}, ${json.latitude} </b>`;
console.log(mydata);
$(".GPSData").html(mydata);
});
</script>
</body>
I'm not 100% sure this is what's causing your issue but I spotted an issue. You didn't include backticks on the line where you're creating your string. You also missed a closing </b> tag.
$.getJSON('https://api.alqimma.com.sa/index.php?key=??&type=live&vehicle=1865', function (json) {
var mydata = `<b>${json.longitude}, ${json.latitude}</b>`;
console.log(mydata);
$(".GPSData").html(mydata);
});
According to the structure of the JSON response, the references you use are invalid. First of all, the response appears to be an array ([...]) of one object. Within that object, the longitude and latitude properties are within the data structure.
So instead of using
var mydata = `<b> ${json.longitude}, ${json.latitude} </b>`;
using this seems to make more sense:
var mydata = `<b> ${json[0].data.longitude}, ${json[0].data.latitude} </b>`;

How to handle non-json data and deserialize it in Flutter?

I'm working on a project in flutter and I'm trying to use an API for CO2 Emissions. The endpoint of the API can be found here: http://www.hqcasanova.com/co2/?callback=callback. I'm having issues parsing the data because it isn't valid JSON notation. Is there a way to handle this inconvenience?
This is the current code I have:
Future<CO2Model> fetchCarbonEmissionData() async {
var response = await http.get('http://www.hqcasanova.com/co2/?callback=callback/');
RegExp exp = new RegExp(r"callback\((.*)\)");
var match = exp.firstMatch(json.encode(response.body));
print(match.group(0));
try {
if(response.statusCode == HTTP_SUCCESS_CODE) {
var jsonData = jsonDecode(response.body);
var data = jsonData['callback'];
CO2Model instance = CO2Model.fromJSON(data);
return instance;
} else {
print('failed');
}
} catch (e) {
throw e;
}
}
Note: Above I tried to use Regular Expressions to deal with this, but I'm unable to do so.
I do not suggest you use a regex for such a simple task, especially if you sure that you will always get something like
callback(...)
you could simply trim spaces, and get the substring you want. However, if you want to do it with regex
r'callback\((.*).*\)'
It basically does what I suggested before, take the match that starts begins with the word callback then group the part of the match you want as output (excluding the trailing parenthesis). I hope this helps.

Asserting entire response body in post man

I recently started working on spring boot projects.
I am looking for a way to assert the entire response of my API.
The intention of this is to reduce the testing time taken for the API.
Found A few solutions mentioned below, but nothing helped me resolve the issue.
pm.test("Body matches string", function () {
pm.expect(pm.response.text()).to.include("string_you_want_to_search");
});
pm.test("Body is correct", function () {
pm.response.to.have.body("response_body_string");
});
When I put the entire response body as an argument, I get the below errors.
Unclosed String
2.
3.
If you want to use the same type of quotes you defined the string with inside it, you have to escape them:
'string with "quotes"'
"string with 'quotes'"
'string with \'quotes\''
"string with \"quotes\""
You probably want to put your json in single quotes as they are not allowed by json itself.
You could try setting the response as a variable and then assert against that?
var jsonData = pm.response.json()
pm.environment.set('responseData', JSON.stringify(jsonData))
From here you can get the data JSON.parse(pm.enviroment.get('responseData')) and then use this within any test to assert against all of the values.
pm.test("Body is correct", () => {
var jsonData = pm.response.json()
pm.expect(jsonData).to.deep.equal(JSON.parse(pm.environment.get('responseData')))
})
My reasoning is that you’re trying to assert against JSON anyway but doing as a plain text string.
Or you could assert against the values separately like this:
pm.test("Body is correct", () => {
var jsonData = pm.response.json()
pm.expect(jsonData[0].employeeName).to.equal("tushar")
pm.expect(jsonData[0].phNum).to.equal(10101010)
})
Depending on the JSON structure you may not need to access an array of data and the [0] can be dropped.

How to format a json string and show result in table?

I am using CakePhp _serialize method to make a web service and show the data in JSON format.I used the .json extension at the end of the URL to show this data.Now i want to show this data in table.Output image is attached.Is this possible then how i can do it?
Thanks
The format is a bit odd. I would prefer something like: "task_list": [ .... ]; iterating over objects is always a bit tedious.
Here is the jQuery code:
var data = ...;
var items = data["task_list"];
var table = $('<table/>');
table.appendTo($('body'));
$.each(items, function(id, value) {
var tr = $('<tr/>');
table.append(tr);
$('<td/>').text(id).appendTo(tr);
$('<td/>').text(value).appendTo(tr);
});

Convert Json response to HTML Table

How do I display all the points in this Json return statement to an HTML table on my view?
return Json(
new
{
vol = exposure.Volatility,
points =
from point in exposure.ExposurePointCollection
select new
{
date = point.ExposureDate,
val = point.MaximumExposure
}
});
If this is the result of an ajax call, you will need to iterate over the collection (presumably the "points" value) and add them to the DOM via javascript. jQuery can help with this, but there are also plug-ins for jQuery that will do virtually all of the work for you, something like jqGrid comes to mind.
Looping through the json result (assuming "points" is what you are looping over)
success: function(data){
jquery.each(data.points, function(index, value){
//index is the index of the array, value is the actual value
});
}
Look here for using jQuery to modify the DOM: http://api.jquery.com/html/#html2