how to deserialize an array of data? - javascript

please help to bring the console dataset.
I do Ajax request and receive a response date as an array:
[{"pk": 2, "model": "app_accounts.userprofile", "fields": {"phone": "21", "other": "<p>qqqqqqdfgdfg</p><p><b>fdg</b></p>", "user_permissions": [], "avatar": "", "skype": "dfsdf", "gender": 2, "groups": []}}]
the problem is that the console does not work and bring
data.pk
and
data.model
screenshot here
$.ajax({
url: "/search_author/",
type: 'POST',
dataType:"json",
data: {
"author": $('#formSearchAuthorWord').val(),
"csrfmiddlewaretoken": $.csrf_token
},
success: function(data) {
console.log(data)
console.log(data.pk)
console.log(data.model)
}
});

That's because it's inside the array.. access them like:
data[0].pk
data[0].model
"[]" brackets represents an array and "{}" an object.
See the DEMO here

Related

JavaScript Object Structure Issue

I am having an issue traversing the objects returned from uploaded file data, but it appears that potentially the object structure that is being returned is preventing me from capturing specific properties from each of the objects in the response or that I am misinterpreting how I should be accessing this object. When I log data.length I get 995, which I assume is the number of characters in the object response. When I log data[prop] It logs each individual character.
Here is my returned file object data:
[
{
"fieldname": "fileUpload",
"originalname": "Screen Shot 2017-01-08 at 12.23.39 PM.png",
"encoding": "7bit",
"mimetype": "image/png",
"size": 39881,
"bucket": "test",
"key": "1/2017-01-23/screen-shot-2017-01-08-at-12.23.39-pm.png",
"acl": "public-read",
"contentType": "image/png",
"contentDisposition": null,
"storageClass": "STANDARD",
"metadata": null,
"location": "https://test.s3.amazonaws.com/1/2017-01-23/screen-shot-2017-01-08-at-12.23.39-pm.png",
"etag": "\"sfasgltg702o\""
},
{
"fieldname": "fileUpload",
"originalname": "Screen Shot 2017-01-08 at 12.21.04 PM.png",
"encoding": "7bit",
"mimetype": "image/png",
"size": 58386,
"bucket": "test",
"key": "1/2017-01-23/screen-shot-2017-01-08-at-12.21.04-pm.png",
"acl": "public-read",
"contentType": "image/png",
"contentDisposition": null,
"storageClass": "STANDARD",
"metadata": null,
"location": "https://test.s3.amazonaws.com/1/2017-01-23/screen-shot-2017-01-08-at-12.21.04-pm.png",
"etag": "\"151353j53j51u5j135ju\""
}
]
jQuery AJAX POST request uploading the files and returning the objects to data:
$.ajax({
url: '/app/sign',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function(data){
console.log('upload successful! ' + data);
console.log('Just the key ' + data.length);
for(var prop in data){
console.log(data[prop]);
}
},
error: function(error){
console.log('error ' + JSON.stringify(error));
}
});
data is a JSON string, you have to parse it back to an array of objects using JSON.parse like this:
success: function(data){
var arr = JSON.parse(data);
// use arr as array
console.log(arr.length);
// arr[0] is the first object
}
It's just a string in JSON format. You need either JSON.parse to convert to a JS object, or use $.getJSON().
Let's say you want to access the first fieldname, you can access it this way data[0].fieldname. The same goes for the second: data[1].fieldname. Why ? because your data is interpreted like this:
0: {"fieldname": "fileUpload", ...}, 1: {"fieldname": "fileUpload", ...}

json, ajax with a hash

i wondering if there any solution to get data from json in this format:
{ "#<Hashie::Mash acceptance_type=1 id=79 name=\"template 1\" url=\"http://myDomain\">":[{"id":68,
"name":"johnny",
"description":"Hello my first Description",
"created_by_user_id":16530,
"created_at":"2016-01-28T13:17:51.827Z",
"updated_at":"2016-01-29T10:40:40.011Z",
"receiver_group_id":3,"dynamic_fields":{
"files":[
{
"id":2,
"date":"2016-01-29T10:40:35.720Z",
"path":"http://mayDomain/000/000/002/original/The_Idiot.pdf?1454064035",
"public":null
}
]} }]}
like i want to have a name and description. but if i call in ajax like this:
$(function(){
$.ajax({
url: './dataModel.json',
dataType: 'json',
method: 'GET',
success: function(data){
console.log(data[0].name);// error name is not defined
console.log(data.name); // undefined
}
});
})
may be you guys have some idea how can i get the name and description? thank you so much for any kind of suggestion and idea.
best regard,
ape
Try this:
var input = {
"#<Hashie::Mash acceptance_type=1 id=79 name=\"template 1\" url=\"http://myDomain\">": [{
"id": 68,
"name": "johnny",
"description": "Hello my first Description",
"created_by_user_id": 16530,
"created_at": "2016-01-28T13:17:51.827Z",
"updated_at": "2016-01-29T10:40:40.011Z",
"receiver_group_id": 3,
"dynamic_fields": {
"files": [{
"id": 2,
"date": "2016-01-29T10:40:35.720Z",
"path": "http://mayDomain/000/000/002/original/The_Idiot.pdf?1454064035",
"public": null
}]
}
}]
};
var output = Object.keys(input).map(function(key) {
return input[key];
})[0];
alert(output[0].name);

Output JSON data using Jquery GET

I'm using Jquery GET to fetch some JSON data that looks like this:
{
"list": {
"meta": {
"type": "resource-list",
"start": 0,
"count": 1
},
"resources": [
{
"resource": {
"classname": "Quote",
"fields": {
"change": "-0.400002",
"chg_percent": "-1.200485",
"day_high": "33.779999",
"day_low": "32.549999",
"issuer_name": "PayPal Holdings, Inc.",
"issuer_name_lang": "PayPal Holdings, Inc.",
"name": "PYPL",
"price": "32.919998",
"symbol": "PYPL",
"ts": "1442606400",
"type": "equity",
"utctime": "2015-09-18T20:00:00+0000",
"volume": "16488139",
"year_high": "42.550000",
"year_low": "30.000000"
}
}
}
]
}
}
I would like to get the value of day_high. Using Jquery I do:
jQuery.ajax({
url: "http://****.com",
type: "GET",
dataType: "json",
async: false,
success: function (data) {
var x = JSON.stringify(data.list.resource.change);
$("p.name").append(x);
console.log(x.change);
}
});
In my console I get:
Uncaught TypeError: Cannot read property 'change' of undefined
I also tried an array approach like data.list.resource[0].change But this outputs:
Uncaught TypeError: Cannot read property '0' of undefined
First, the variable x cannot be interpreted as JSON with your console logging statement because JSON.stringify converts it to a string. Second, it looks like you have your path mixed up. It should be data.list.resources[0].resource.fields.change.
You can try this:
var x = JSON.stringify(data.list.resources[0].resource.fields.change);
The error was with your path.

ajax in jquery error : converting circular structure to JSON

I console JSON.stringify(stateArr) my json look fine and look like this
{
"shipping_options": [{
"id": "1",
"name": "Kuala Lumpur",
"rate": "222"
}, {
"id": "2",
"name": "Labuan",
"rate": "1"
}]
}
but I got converting circular structure to JSON error with my below code, I wonder why?
param["state"] = stateArr;
$.ajax({
type: "POST",
url: 'example.com',
data: {
type: "json",
data: JSON.stringify(param)
},
cache: false,
async: false,
timeout: 10000,
success: function(data) {
alert('ok');
},
error: function(response) {}
});
I think you have something like
var param = stateArr;
param["state"] = stateArr;
This is a circular structure. Check your param reference.

Breaking Out JSON Result Into Localstorage Key/Value Pairs

I have a valid JSON result:
{
"metadata": [
{
"name": "md1",
"value": "blah1"
},
{
"name": "md2",
"value": "blah2"
},
{
"name": "tee2",
"value": "blah3"
}
],
"subdata1": [
{
"name": "sd1_1",
"value": "blah1_1"
},
{
"name": "sd1_2",
"value": "blah1_2"
},
{
"name": "sd1_3",
"value": "blah1_3"
},
{
"name": "sd1_4",
"value": "blah1_1"
}
],
"subdata2": [
{
"name": "sd2_1",
"value": "blah2_1"
},
{
"name": "sd2_2",
"value": "blah2_2"
},
{
"name": "sd2_3",
"value": "blah2_3"
}
]
}
coming in via a successful jQuery .ajax() call:
$.ajax({
url: 'test.json',
type: 'get',
datatype: 'json',
processData: false,
success: function(data) { //do something...};
It's relatively easy to blob the entire result into a value associated with an overall key:
localStorage.setItem('newtest', data);
This would save the entirety of my JSON response as a value with a key called "newtest". But suppose I want each array's descriptor as the key name and the associated array as the value? In my example, that would give me three key/value pairs, with each array saved as a separate string value associated with keys named "metadata," "subdata1" and "subdata2", respectively. I've done a great deal of searching but have not come across the correct approach for this. Any help towards a solution would be greatly appreciated -- thank you for your attention and assistance.
You can do a for loop and stringify the objects.
$.ajax({
url: 'test.json',
type: 'get',
datatype: 'json',
processData: false,
success: function(data) {
for(var key in data){
localStorage.setItem(key, JSON.stringify(data[key]));
}
}
});
Then parse when you get them
JSON.parse(localStorage.getItem("metadata"));

Categories