JavaScript Object Structure Issue - javascript

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", ...}

Related

Where is image data in React?

Im using the following function to upload an image to our application:
const result = await ImagePicker.launchCameraAsync({
allowsEditing:true,
});
This returns the following object:
Object {
"cancelled": false,
"height": 3200,
"type": "image",
"uri": "file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540sepbaa%252Frepoflex/ImagePicker/ff4dc82d-f14b-4b23-a81a-30e87c34d7e0.jpg",
"width": 2400,
}
Afterwards we need to upload the image to our backend, but we don't know where the image data is. If we do a fetch to the uri from the previous object, it returns the following:
Object {
"_bodyBlob": Object {
"_data": Object {
"collector": Object {},
"blobId": "c0e241fa-9b39-4aed-9860-793a393408dd",
"lastModified": 0,
"name": "ff4dc82d-f14b-4b23-a81a-30e87c34d7e0.jpg",
"offset": 0,
"size": 4864483,
"type": "image/jpeg",
},
},
"_bodyInit": Object {
"_data": Object {
"collector": Object {},
"blobId": "c0e241fa-9b39-4aed-9860-793a393408dd",
"lastModified": 0,
"name": "ff4dc82d-f14b-4b23-a81a-30e87c34d7e0.jpg",
"offset": 0,
"size": 4864483,
"type": "image/jpeg",
},
},
"bodyUsed": true,
"headers": Object {
"map": Object {
"content-type": "image/jpeg",
},
},
"ok": false,
"status": 0,
"type": "default",
"url": "",
}
We need to send to our backend the raw image bytes. Where is that data stored? How can we retrieve it?
For uploading it to backend you need to do like this
const form = new FormData();
form.append({
name: "SampleImage.jpg", // Name of file
uri: "file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540sepbaa%252Frepoflex/ImagePicker/ff4dc82d-f14b-4b23-a81a-30e87c34d7e0.jpg", // URI of the file
type: "image/jpg", // MIME type of the file
})
Now you just simply have to perform a POST request with this form as body
Also in the backend you can access it like this
req.file // Depends on the backend you are using ...

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.

Read json data in PHP sent with an Ajax call

A front-end developed is sending a array of data formated as a JSON object with an Ajax call.
The json object looks like this:
{
"name": " Test Name ",
"image_url": "test URL",
"include": [
"1"
],
"dimension": [
null
],
"media_type": [
null
],
"match": [
"1"
],
"content": [
"test content"
],
"sorting": {
"rating": "50",
"language": "50",
"CS Weight": "50",
}
}
How I can read it in my PHP controller. Can I just get it just this way:
$data = $_POST;
Because the variable that contains the JSON object in this case has no name, I cannot get it this way
$data = $_POST['data']
Edited Part
From the front-end, the data is sent this way:
sendAjax: function(value, url, callback){
xhr = $.ajax({
type: 'POST',
url: url,
data: value
}).done(function(message){
callback(message);
}).fail(function(jqXHR, textStatus){
console.log('failed to submit form, error type: '+textStatus);
});
}
Read it from the script's input, which is where you can get the "raw" POST data:
$json = file_get_contents('php://input');
$data = json_decode($json);
This should work assuming you're using jquery on your front end. Just paste this into your javascript console and run it (make sure you replace the path with your web address. The parameters should come through correctly.
data = {
"name": " Test Name ",
"image_url": "test URL",
"include": [
"1"
],
"dimension": [
null
],
"media_type": [
null
],
"match": [
"1"
],
"content": [
"test content"
],
"sorting": {
"rating": "50",
"language": "50",
"CS Weight": "50",
}
}
$.ajax({url:'/YOUR/PATH/HERE', data: {data: data}, type: 'post', dataType: 'json'})
Occurred to me after posting, are you asking how do you parse the JSON once received or how to get it to show in the $_POST hash?

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

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