Breaking Out JSON Result Into Localstorage Key/Value Pairs - javascript

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"));

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);

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.

^How to parse multiple JSON arrays received from server?

Here is my Json Data received from Server:
[
{"Name":"A"},
{"Name":"B"},
{"Name":"C"},
{"Name":null}
]
[
{"Name":null},
{"Name":"D"},
{"Name":null}
]
[
{...},
{...}
]
How do I parse it using using JQUERY in AJAX success attribute?
Here is my Ajax code:
$.ajax({
url: '#.php',
type: 'post',
async: false,
data: {},
dataType: 'json',
success: function(data){
var str = JSON.stringify(data);
var obj = JSON.parse(str);
for(var i=0; i< data.length;i++)
{
alert(data[i].Name);
}
},
complete: function(xhr,status){
alert(status);
},
error: function(xhr){
alert("An error occured: " + xhr.status + " " + xhr.statusText );
alert("An error occured. Please Try Again");
}
})
This code is not working and giving parser error on complete.
I want to Display all the Names received.
Please Help.
your data received from the server are not valid JSON, if it was, it would be
something like :
[
[{
"Name": "A"
}, {
"Name": "B"
}, {
"Name": "C"
}, {
"Name": null
}],
[{
"Name": null
}, {
"Name": "D"
}, {
"Name": null
}]
]
that would be even easier to parse:
[{
"Name": "A"
}, {
"Name": "B"
}, {
"Name": "C"
}, {
"Name": null
}, {
"Name": null
}, {
"Name": "D"
}, {
"Name": null
}]
The data returned by your server does not respect JSON syntax.
In order to have a proper JSON structure, there should be only one parent object and not multiple arrays.
If you can modify your server's output, consider the following alternatives:
Creating a parent array:
[ your_arrays ]
then access to data[0] to retrieve your arrays in your success function.
Creating a parent object:
{myArrays : your_arrays}
then access to data.myArrays in your success function.

how to deserialize an array of data?

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

Categories