How can i fetch data from an array in json object? - javascript

I want to fetch the values in the List array from the json object.
Here is my JS / Ajax code:
$.ajax({
type: 'GET',
url: "http://127.0.0.1:8000/api/sort_api/" + a,
contentType: 'application/json',
dataType: 'json', //specify jsonp
success: function(data) {
var htmlData= '';
for(var i=0; i<data.length; i++){
htmlData+= '<li>'+data[i]+' </li>';
}
$('#list').html(htmlData);
// alert(list);
console.log(data);
}.bind(this),
error: function(e) {
console.log('error', e);
}
});
Here is the console log(data) result:
{status: "200", status_message: "List Sorted", List: Array(5)}
List:(5) ["Abc", "Take 78A", "Take Airport", "Take flight", "Take flight"]
status:"200"
status_message:"List Sorted"
When i write console.log(data['status'])
It shows the value 200 in console
But when i write console.log(data['list']);
it shows undefined
Can somebody tell me what i am missing?
I want to retrieve the array(List) in that object

Try with each
$.each(data, function( index, value ) {
htmlData+= '<li>'+value+' </li>';
});

try in capital List not list
console.log(data.List)
or
console.log(data['List'])
both will work.

Related

Why does my JSON data with Ajax not return correctly even though the console logs it?

I am getting a number (1,2,3, etc.) based on coordinates like this:
function getNumber(lat,lng)
{
var params="lat="+lat+"&long="+lng;
$.ajax({
type: "POST",
url: "https://www.page.com/code.php",
data: params,
dataType: 'json',
success: function(data){
if (data.valid==1){
console.log(data);
$("#number").html(data.number);
} else {
console.log(data);
}
},
error: function(){
}
});
}
The problem is, when I check the console, the data is there like this:
[Object]
0 Object
lat: 100.00
long: 50.00
number: 1
etc.
Why doesn't it let me parse it?
The way I return it with POST is:
[{"valid":"1","lat":100.00,"long":50.00,"number":"1"}]
So you are returning an array?
Then you need to refer to the data by index:
data[0].valid==1

this.state.search_results.map is not a function but it's an array

render: function(){
console.log(this.state.search_results);
var renderedSearchResults = this.state.search_results.map((result) => {
The console.log prints:
[{"id": "testGroup2"}, {"id": "testGroup77777"}, {"id": "testGroup1"}, {"id": "testGroup3"}]
The data is obtained through:
$.ajax({
url: this.props.routes.search,
contentType: 'application/json',
type: 'POST',
data: JSON.stringify(searchObj),
success: function(data){
console.log(data);
this.setState({search_results:data});
}.bind(this),
error: function(xhr, status,err){
console.error("/api/response", status, err.toString());
}.bind(this)
});```
Through:
def post(self):
"""
Makes a request to search for a specific
searchtype: Group
searchstring: ""
requestedfields: []
"""
search_type = self.json_data.get('searchtype', 'Group')
search_string = self.json_data.get('searchstring', '')
requestedfields = self.json_data.get('requestedfields', ['id'])
search_model = {
'Group': Group(),
'User': User()
}[search_type]
search_fields = {
'Group': ['id', 'tags'],
'User': ['username']
}[search_type]
# check if requestedfields contains valid fields
for field in requestedfields:
if field == 'id':
continue
value = search_model.default().get(field, None)
if value is None:
return self.set_status(400, "Model {0} does not have requested field {1}".format(search_type, field))
try:
search_results = search_model.search_items(search_string, search_fields, requestedfields)
except err:
return self.set_status(400, "Something went wrong")
self.set_status(200, "Success")
return self.write(tornado.escape.json_encode(search_results))
I'm really confused as to how this.state.search_results isn't an array that I can iterate through, can anyone see what's going on?
I've tried using console.log(Object.prototype.toString.call(data)); inside the success function and I get:
[object String]
Try to set json data type in an explicit way, while doing your ajax request:
$.ajax({
dataType: 'json',
//...
});
Most probably Intelligent Guess that is used to detect data type by jQuery, is giving wrong result.
Found my answer, didn't set dataType: "json" in my ajax request.

Parsing JSONP file with JavaScript

How do I access the Marie-Antoinette.json object in this JSON file? I would like to get the title element of the object but I can't seem to get it to output. Here is my JavaScript code which outputs the object but I cant seem to access the objects elements.
$.ajax(
{
type: 'GET',
url: 'http://localhost:5984/movies/efadd5913f5cfd254b2861efd4001cb7',
//contentType: "application/json; charset=utf-8",
dataType: "JSONP",
jsonpCallback: 'callback',
//async: false,
success: function(r)
{
alert("ok");
$.each(r, function(index, value){ // iterating over each object
console.log(index);
if(index == "_attachments")
{
console.log(value); //how do I output the title ("Marie-Antoinette.json") and the other stuff in the object?
}
});
}
});
Here is the file. The elements I would like to access are in the "_attachments" element of the object.
{
"_id": "efadd5913f5cfd254b2861efd4001cb7",
"_rev": "6-417588bbff9aa74726b11440a86a8532",
"_attachments": {
"Marie-Antoinette.json": {
"content_type": "application/json",
"revpos": 2,
"digest": "md5-Io/Pxakfp/4R8ntjQKWMDg==",
"length": 761,
"stub": true
}
}
}
I think what is throwing me off is that it is an object inside the _attachment section.
The Marie-Antoinette.json object is inside your _attachments object, but because it contains a . it can't be accessed using dot-notation. You'll have to use array-like notation, passing the key as a string like so:
success: function (response) {
console.log(response._attachments['Marie-Antoinette.json']);
}
If you have multiple "attachments", you can access them in a loop like this:
success: function (response) {
$.each(response._attachments, function (i, attachment) {
console.log(attachment);
});
}
You could use Object.keys to extract keys from _attachments object and then print it:
var title = Object.keys(r._attachments)[0];
console.log(title);
Or if you have multiple attachments:
var titles = Object.keys(r._attachments);
console.log(titles.join());
Object.keys always returns an array.
in your function:
success: function(r)
{
for (key in json._attachments) {
console.log(key); // gives the names
console.log(json._attachments[key]); // gives the content
}
}
that would give you the stuff in _attachments

How can I convert a json object to an array in javascript

Here is a snippet of javascript from my C# web MVC application:
$.ajax({
url: 'myurl'
}).done(function(response) {
$scope.Vdata = JSON.parse(response);
return $scope.$apply();
});
The JSON response form this call looks like this
"{
\"renditions\": {
\"live\": \"true\",
\" type\": \"default\",
\"rendition\": {
\"name\": \"Live \",
\"url\": \"http: //mysite\"
}
}
}"
I would like to wrap the json response rendition object into an array to look like this-(note the added square brackets for the array)
"{
\"renditions\": {
\"live\": \"true\",
\" type\": \"default\",
\"rendition\": [{
\"name\": \"Live \",
\"url\": \"http: //mysite\"
}]
}
}"
I tried something like this which didn’t work:
$.ajax({
url: 'myurl'
}).done(function(response) {
var tmp;
if (!respose.renditons.rendition.isArray) {
tmp = respose.renditions.renditon;
respose.renditon = [];
respose.renditon.push(tmp);
}
$scope.Vdata = JSON.parse(response);
return $scope.$apply();
});
The response will sometimes include the rendition object as an array so I only need to convert to an array in cases where its not.
Can someone please help me with the correct javascript to convert the json object into an array. Preferably modifying my existing code
Try this:
$.ajax({
url: 'myurl'
}).done(function(response) {
var json = JSON.parse(response);
if(!Array.isArray(json.renditions.rendition)) {
json.renditions.rendition = [json.renditions.rendition];
}
return json;
});
Fiddle demo (kind of...)
You can check if the object is an array using this:
Object.prototype.toString.call( response.renditions.rendition ) === '[object Array]'
And you can simplify the conversion to an array -- just wrap it as an array using x = [x]:
if (Object.prototype.toString.call( response.renditions.rendition ) !== '[object Array]') {
response.renditions.rendition = [response.renditions.rendition];
}
Fiddle demo.
add data type JSON to your ajax post. example
$.ajax({type: "POST",
url: URL,
data: PARAMS,
success: function(data){
//json is changed to array because of datatype JSON
alert(data.renditions);
},
beforeSend: function (XMLHttpRequest) {
/* do something or leave empty */
},
complete: function (XMLHttpRequest, textStatus) { /*do something or leave empty */ },
dataType: "json"}
);

Javascript alert if JSON response has designated row

I'm trying to build an app that gets JSON from server and then shows a javascript alert if the JSON response has designated row. The JSON I get from server looks like this:
{
"key": [
{
"IND": "406",
"NUMBER": "9",
"MESSAGE": "this is a test",
"status": "ok"
}
]
}
And this is the code I use to show the alert:
function UpdateRecord(update_id) {
var id = getUrlVars()["id"];
jQuery.ajax({
type: "POST",
url: serviceURL + "test.php",
data: 'id=' + id,
cache: false,
success: function(data) {
if (data.status == 'ok') {
alert(data.message);
} else {
alert("no");
}
}
});
}​
But this code alerts "no" even though the JSON has a row "status": "ok"
Try with if (data.key[0].status), and replace alert(data.message) with alert(data.key[0].MESSAGE). You have to be careful with capitalization!
you have "key" defined in your jSON, sohould it not be
if(data.key[0].status == "ok")
Do a console.log(data) in the success handler to see what the data is. You will see that there is no data.status, but instead it would be data.key[0].status.

Categories

Resources