Parsing a JSON Object with multiple Sub-Objects - javascript

<script type="text/javascript" src="http://static.stackmob.com/js/2.5.3-crypto-sha1-hmac.js"></script>
<script type="text/javascript">
$j.ajax({
dataType : 'json',
url : "/api/core/v2/groups/", //or any other rest call here
beforeSend: function(xhr) {
var bytes = Crypto.charenc.Binary.stringToBytes('username' + ":" + 'password');
var base64 = Crypto.util.bytesToBase64(bytes);
xhr.setRequestHeader("Authentication", "Basic " + base64);
},
success: function(data, status, xhr) {
console.log("success!");
console.log(data);
console.log(data[0]);
}
});
The output of data is
Object
data: Array[25]
0: Object
contentTypes: Array[4]
creationDate: "2012-05-31T20:21:20.532+0000"
creator: Object
description: "A discussion group for anyone interested in amateur radio."
displayName: "amd-amateur-radio-forum"
followerCount: 5
groupType: "OPEN"
id: 1133
memberCount: 3
modificationDate: "2012-06-04T21:23:07.078+0000"
name: "AMD Amateur Radio Forum"
resources: Object
type: "group"
viewCount: 62
__proto__: Object
1: Object
2: Object
3: Object
but when I try to output data[0] or data[1] they all come back as undefined.
I am not sure how to deal with this JSON object.
The output of alert(data) is
[Object object]
so I am assuming it is a properly formatted JSON object.
Here is the output JSON.stringify(data)
{"data":[{"contentTypes":["discussions","documents","blog","projects"],"memberCount":3,"creator":{"name":"firstname lastname","level":{"name":"Level I","description":"null","points":7,"resources":{"image":{"ref":"http://connect-dev.amd.com/api/core/v2/images/status/statusicon-47.gif","allowed":["GET"]}}},"username":"dkyle","email":"david.kyle#amd.com","firstName":"firstname","lastName":"lastname","resources":{"self":{"ref":"http://connect-dev.amd.com/api/core/v2/users/4183","allowed":["GET"]},"avatar":{"ref":"http://connect-dev.amd.com/api/core/v2/users/4183/avatar","allowed":["GET"]}},"id":4183},"groupType":"OPEN","name":"AMD Amateur Radio Forum","displayName":"amd-amateur-radio-forum","description":"A discussion group for anyone interested in amateur radio.","followerCount":5,"resources":{"projects":{"ref":"http://connect-dev.amd.com/api/core/v2/groups/1133/projects","allowed":["GET"]},"invites":{"ref":"http://connect-dev.amd.com/api/core/v2/groups/1133/invites","allowed":["POST"]},"documents":{"ref":"http://connect-dev.amd.com/api/core/v2/groups/1133/documents","allowed":["GET","POST"]},"html":{"ref":"http://connect-dev.amd.com/groups/amd-amateur-radio-forum","allowed":["GET"]},"self":{"ref":"http://connect-dev.amd.com/api/core/v2/groups/1133","allowed":["GET"]},"blog":{"ref":"http://connect-dev.amd.com/api/core/v2/blogs/1368","allowed":["GET"]},"members":{"ref":"http://connect-dev.amd.com/api/core/v2/groups/1133/members","allowed":["GET"]},"discussions":{"ref":"http://connect-dev.amd.com/api/core/v2/groups/1133/discussions","allowed":["GET","POST"]}},"id":1133,"type":"group","creationDate":"2012-05-31T20:21:20.532+0000","modificationDate":"2012-06-04T21:23:07.078+0000","viewCount":62},{"contentTypes":["discussions","documents","blog","projects"],"memberCount":34,"creator":{"name":"firstname lastname","level":{"name":"Level I","description":"null","points":24,"resources":{"image":{"ref":"http://connect-dev.amd.com/api/core/v2/images/status/statusicon-47.gif","allowed":["GET"]}}},"username":"username","email":"kristi.fontenot#amd.com","firstName":"firstname","lastName":"lastname","resources":{"self":{"ref":"http://connect-dev.amd.com/api/core/v2/users/4291","allowed":["GET"]},"avatar":{"ref":"http://connect-dev.amd.com/api/core/v2/users/4291/avatar","allowed":["GET"]}},"id":4291},"groupType":"OPEN","name":"AMD Community Corps Connect (Matching Gifts, GIVE and Volunteerism)","displayName":"amd-community-corps-connect-matching-gifts-give-and-volunteerism","description":"Through this community, employees are be able to support the causes they care about most in ways thev have never been able to before. Not only that, employees will be able to connect and network with fellow AMD employees in a way that allows everyone connected to each other to volunteer together, while providing the ability to track volunteer hours, make charitable contributions and request a match all in the same tool. \r\n\r\nhttp://amd.yourcause.com \r\n\r\n","followerCount":55,"resources":{"projects":{"ref":"http://connect-dev.amd.com/api/core/v2/groups/1074/projects","allowed":["GET"]},"invites":{"ref":"http://connect-dev.amd.com/api/core/v2/groups/1074/invites","allowed":["POST"]},"documents":{"ref":"http://connect-dev.amd.com/api/core/v2/groups/1074/documents","allowed":["GET","POST"]},"html":{"ref":"http://connect-dev.amd.com/groups/amd-community-corps-connect-matching-gifts-give-and-volunteerism","allowed":["GET"]},"self":{"ref":"http://connect-dev.amd.com/api/core/v2/groups/1074","allowed":["GET"]},"blog":{"ref":"http://connect-dev.amd.com/api/core/v2/blogs/1267","allowed":["GET"]},"members":{"ref":"http://connect-dev.amd.com/api/core/v2/groups/1074/members","allowed":["GET"]},"discussions":{"ref":"http://connect-dev.amd.com/api/core/v2/groups/1074/discussions","allowed":["GET","POST"]}},"id":1074,"type":"group","creationDate":"2012-05-07T19:24:31.880+0000","modificationDate":"2012-09-07T02:00:51.821+0000","viewCount":544}
It is actually longer than that

If you are outputting stringifying data and you have inside that an array named data then you need to do data.data[0] instead of data[0].
It would be a little more clear for you if you said:
success: function(result, status, xhr){
var data = result.data;
Then data[0] would work just fine.

Related

Jquery Ajax passing array inside data obect

I am trying to pass an object into the data property of this jquery ajax request. All work's fine, but the fields property, which is an array, does not get recognized (returns all fields, when these are the two I am requesting).
I've tried JSON.stringify, but this returns an error for 'bad request'. How do I pass this object with an array inside correctly?
function energyQuery(token){
$.ajax({
type: 'GET',
url: url,
headers: {'Content-Type': 'application/json', 'Authorization': 'Token token=' + token},
data: {
'start': '2019-01-05',
'end': '2019-01-10',
'limit': 0,
'measurement': 'analysis',
'fields': ['energy_out', 'energy_in'] // if I pass 'energy_out' it works
},
success: function(data){
//console.log(data);
response = JSON.stringify(data);
console.log(response);
},
error: function(errMsg) {
console.log('Query:' + JSON.stringify(errMsg));
}
});
}
error message:
Please note that fields MUST either be a single valid field string or a list of valid field strings.
Send it as post and point to correct datatype
var array = ['energy_out', 'energy_in'];
var dataObj = {
'start': '2019-01-05',
'end': '2019-01-10',
'limit': 0,
'measurement': 'analysis',
'fields': array
};
var data = JSON.stringify(dataObj);
$.ajax({
url: url,
type: "POST",
dataType: "json",
data: data,
contentType: "application/json"
});
Also on back-end side create correct model to recieve data.
If you are implementing also the server side, please consider to change the array of strings to a "particular string".
What I mean?
CASE 1 : pass array as string
'fields': '[\'energy_out\', \'energy_in\'])'
Then in the server side read the string and convert it to an array.
This is the solution that I use in Java: I read a String then I convert it to an array of integer,strings,... and so on.
CASE 2: use a particular separator, pass the field as a string;
'fields': 'value1,value2,value3'
Supposing you use , as separator, then you must split string by ,.
It's better to ask (via web service) arrays as a single string so each client can implement in a simple way of to pass data in the get method.
'fields': ['energy_out', 'energy_in']
It's not a standard json format. just change the type of parameter 0 'fields': 'energy_out,energy_in' and when receive use split,

pasring JSON from string in jQuery

http://localhost/project1/index.php
//AJAX region
$(function(){
$.ajax({
type : 'GET',
url : 'https://jsonplaceholder.typicode.com/posts/1',
success : function(data){
console.log('success \n', data);
},
error : function(data){
console.log('error', data);
}
});
});//AJAX region
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
it's easily loading data from http://localhost/project1/json.php
console:
data is string, if I use $.parseJSON(data) or JSON.parse(data) i get following error...
I want data as realtime JSON object, so that I can access each properties & values.
Observation 1: unnecessary parseJSON
No need to call parseJSON.
Use dataType property of $.ajax to load your data directly in JSON format:
$.ajax({
type : 'GET',
dataType: 'json', // here
url : 'http://localhost/project1/region.php',
success : function(data) {
// data is already a JS object :)
console.log('success \n', data);
},
error : function(data){
console.log('error', data);
}
});
Observation 2: wrong JSON
Code above will still throw the same error, because of
unexpected token ,
It refers to the trailing comma after all the last elements your object and its children. Remove that comma and there will be no more errors.
For example:
"State1" : {
"City 1",
"City 2",
"City 3",
}
There should NOT be a comma after "City 3". The same goes for other states, and for whole "country2" object too.
There is another error: your States objects are arrays, but you are writing then as objects. Change curl brackets to square brackets for "State1" and "State2".
The json object you are returning is invalid json, for the state objects, you need to make them arrays. so:
"State1":["City1","City2","City3"]
When the parser parses this object it expects a second value per city like "City1 ": "Second Value"...since there is no second value its breaking.

Posting an array of objects to MongoDB with Node sends empty array

I am trying to POST an array of objects to my MongoDB database using NodeJS. When I post, all my fields show up empty. I put my code below, and below that explain what each of the console.logs output. Any ideas how to sort this out?
MODEL
var mongoose = require('mongoose');
var TransferSchema = new mongoose.Schema({
uploadDate: Date,
period: Number,
transferCode: String,
voucherNumber: String,
vendor: String,
description: String,
amount: Number
});
//convert schema to model
var Transfer = mongoose.model('Transfer', TransferSchema);
//export model for use elsewhere in app
module.exports = Transfer;
AJAX
- here I've tried posting both newArray and json. Both result in the same data posted to my db, but have a different effect on the console.logs in the controller file.
console.log(newArray);
json = JSON.stringify(newArray);
console.log(json);
$.ajax({
url: "http://localhost:3000/transfers/api",
type: "POST",
data: newArray,
datatype: 'json',
success: function(data, textStatus, jqXHR) {
console.log('posted!');
},
error: function(data, textStatus, errorThrown) {
console.log('failed');
}
})
transferController.js
-when posting newArray I get the following:
body: [object Object],
Body: {"undefined": ["", "", "", etc],
Text: undefined,
Done: undefined
-when posting json I get the following:
body: [object Object],
Body: {"{\"period\":5,\"uploadDate\":2015-11-19T21:00:00.000Z\",\"transferCode\":\"1041\",\"vendor\":\"Lakes State\",\"voucherNumber\":\"0000047571\",\"description\":\"1003-1555 Sal Tax Adj Gran Sep \",\"amount\":456802}...,
Text: undefined,
Done: undefined
//Create a new transfer
function createTransfer(request, response) {
console.log('posting');
console.log('body: ' + request.body); //TEST
console.info("Body: " + JSON.stringify(request.body)); //TEST
console.info("Text: " + JSON.stringify(request.body.text)); //TEST
console.info("Done: " + JSON.stringify(request.body.done)); //TEST
var transfer = new Transfer(request.body);
transfer.save(function(error) {
// console.log('transfer and transfer: ' + transfer);
if(error) return response.json({ message: 'could not create transfer because ' + error });
response.json({ transfer: transfer });
});
}
EDIT:
I tried using Insomnia to test what I'm sending. Weirdly, the below screenshot posts on Insomnia, but does not post in my app:
Also interesting, if I post several objects in an array using Insomnia, it does not work, as seen below:
Try setting contentType: 'application/json' in your ajax request and stringify your data like so JSON.stringify(newArray). This should ensure the data you are sending up is ok.
It looks like you are sending up many transfers but then trying to create one transfer from all the data (request.body)? You would need to loop over them and create them individually. Something like this:
request.body.forEach(function(obj) {
var transfer = new Transfer(obj);
transfer.save();
});

JSON parsing in javascript, the data is always undefined [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 7 years ago.
I am currently trying to parse a random JSON file online, you can try the link and look at it for yourself. No matter what I look for, I always get 'undefined' when accessing the data. I just want to get some sort of output from the json. For example, how can I get the list of names ('nm') in the file? No matter what I do, it always gives me undefined.
$.ajax(
{
type: 'GET',
url: 'http://mysafeinfo.com/api/data?list=englishmonarchs&format=json',
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(r)
{
alert(r.example);
}
});
The data fetched from that API is an array of objects like this.
[{
nm: "Edward the Elder",
cty: "GB",
hse: "House of Wessex",
yrs: "899-925"
}, {
nm: "Athelstan",
cty: "GB",
hse: "House of Wessex",
yrs: "925-940"
}]
One of the ways to iterate over the array of objects is $.each
success: function(r)
{
$.each(r, function(index, value){ // iterating over each object
console.log(value.nm); // <---- accessing nm of each object
});
}
You are not iterating upon the result set.
This is much shorter and readable.
$.getJSON("http://mysafeinfo.com/api/data?list=englishmonarchs&format=json", function (data) {
$.each(data, function (index, value) {
alert(index + ": " + value.nm);
});
});
http://jsfiddle.net/5skony7y/2/
Open the Chrome console and you will see the following:

Parsing response text as key value pairs in an elegant way

Can't seem to find what I'm looking for in searches so this might be a duplicate but I haven't found an original yet sooo....
I have a an ajax call:
$.ajax({
url: "/events/instructor/",
type: 'POST',
data: {
instructorID: $(this).attr("id")
},
complete: function (data) {
$("#name").html(data["responseText"]["name"]);
$("#email").html(data["responseText"]["email"]);
$("#photo").html(data["responseText"]["photo"]);
$("#summary").html(data["responseText"]["summary"]);
$("#url").html(data["responseText"]["url"]);
}
});
The data being returned is encoded in JSON by the server (C#).
Obviously, data["responseText"]["fieldName"] isn't doing the trick. I could do splits and whatnot but that would mean that if the format changes, I'd need to make sure that the code above keeps up with the changed shape of the data.
How can I say something as simple as data["responseText']["fieldName"] to get the value out of that key?
i think you need to parse json first. look at the api.jquery.com/jquery.parsejson
// data = '{ "name": "John" }'
var obj = jQuery.parseJSON( data );
console.log( obj.name);
// result will be "John"
P.S. also better use 'succes' instead 'complete', you can read about this here Difference between .success() and .complete()?
success: function(data) {
console.log("response is good", data);
},
error: function (){
console.log("something is went wrong");
}
try using like this:
complete: function (data) {
var data=JSON.parse(data);
$("#name").html(data.responseText.name);
$("#email").html(data.responseText.email);
$("#photo").html(data.responseText.photo);
$("#summary").html(data.responseText.summary);
$("#url").html(data.responseText.url);
}
to get only correct response use success.

Categories

Resources