I wanting to replicate this array structure in Javascript, but I cannot figure out how to do it, in my php I have the following,
$myArray = array();
$myArray['location1'] = array('name' => 'Texas', 'person' => 'Jim');
$myArray['location2'] = array('name' => 'California', 'person' => 'Jeff');
This would leave me a structure that looks like,
myArray = array(
'location1' = array('name' => 'Texas', 'person' => 'Jim')
'location2' = array('name' => 'California', 'person' => 'Jeff')
)
What I wanting in javascript is an array that holds other arrays and the sub arrays are keyed is this possible?
As stated by Steven, Javascript Arrays are not associative. However, you can parse an Associative PHP Array as a JSON Object which will led to the same structure when passing from or to Client Side.
P.E In PHP you'd have
$myArray = [
"tag"=>"property",
"properties"=>[
"color"=>"blue",
"name"=>"A Name"
]
];
Then, you return this array as JSON
return json_encode($myArray);
And when you receive it on Javascript you do a JSON Parse with the response
function getMyObject()
{
// Code for retrieving the JSON From Server
//End of Code for JSON Retrieval
const myObject = JSON.parse(response);
}
This will led to an structure such as this in Javascript
console.log(myObject)
>>>>
{
tag:"property",
properties:{
color:"blue",
name:"A Name"
}
}
Which you can access with the object.key notation or object[key] in Javascript.
Most of frameworks do this in a transparent way. For example, if you're using Laravel when you return the Array as a response in an API route, it will automatically parse it as a JSON. And then, in a framework such as Angular, the HttpClient will automatically parse the JSON response as a JavaScript object.
Then, in the opposite direction, if you send a object to an Endpoint. It will automatically be converted to a JSON body in the request and parsed by the backend framework.
Related
I have a JSON file which has this:
[
{
"id":"1",
"customer":{
"nickname":"nick001",
"email":"",
"id":"15615",
"name":"Smith Dole",
"phone":"5555555"
},
"totalorder":"44155",
"items":[
{
"code":"041545420",
"title":"item",
"quantity":1,
"price":"2461.7500",
"subtotal":2461.75
}
]
}
]
As you can see it doesn´t have any parent root name. How can I read this JSON with JavaScript ?
I was thinking to PARSE the Json but JSON.parse(need the name)
Is it possible to call this JSON in my JavaScript code and asign it a variable ?
var newSelling = data from the JSON
The JSON is being generated by another system which generates it that way so I need to read the JSON to get the data needed for other processes
the JSON is automatically generated and it is in an external file
So it is a JSON file. Request it with fetch or XMLHttpRequest and access the JSON.
fetch('/path/to/your/file.json')
.then(response => response.json())
.then(data => {
console.log(data)
});
If you want to read the file in the Browser from your local you can use one of these solutions :
Fetch API.
Axios.
XMLHttpRequest.
I recommend Fetch API.
fetch("data.json")
.then(response => response.json())
.then(json => console.log(json));
It works in Firefox, but in Chrome you have to customize security setting.
If you look carefully, you'll see that this JSON file is just a JSON array with only one Object inside of it. So you have to access the object that is in the array.
let arr = JSON.parse(*the json object*);
let obj = arr[0];
I haven't tested this, but hopefully this helps.
Here in your case, using JSON.parse only is not working
but the combination of JSON.stringify and JSON.parse is working as I tried.
So first, we can stringify it and then we can parse it
Like this :
var a = [
{
"id":"1",
"customer":{
"nickname":"nick001",
"email":"",
"id":"15615",
"name":"Smith Dole",
"phone":"5555555"
},
"totalorder":"44155",
"items":[
{
"code":"041545420",
"title":"item",
"quantity":1,
"price":"2461.7500",
"subtotal":2461.75
}
]
}
];
var b = JSON.stringify(a);
var c = JSON.parse(b);
console.log(c[0].id); //output : 1
Parsing JSON should work as follows:
const json = '{"result":true, "count":42}';
const obj = JSON.parse(json);
console.log(obj.count);
// expected output: 42
console.log(obj.result);
// expected output: true
More info
Edit:
You can red this question. I think it may help
I don t know why data formated as json using JSON.parse function return as Array type when I want to check the new converted type.
First I made ajax request to go and fetch data from a database as illustrated below
$.ajax({
url:'processBet.php',
data:'',
success:function(data){
//below I check the return data type
console.log( Object.getPrototypeOf(JSON.parse(data)));
//the return type is array.....why?
console.log((JSON.parse(data)); // to see the data
}
});
Obviously in the file that fetch data in the database will put data in Array.So before sending it I converted it in JSON using a php function json_encode as illustrated below
$ql = "SELECT * from tempdata" ;
$result=$pdo->query($ql);
$result->setFetchMode(PDO::FETCH_ASSOC);
while($data = $result->fetch()){
$arrays[]=$data;
}
//Now I convert in json before sending
$json =json_encode($arrays);
echo $json; // the return data supposed to be json type
Below is the sample of the data return after succeessfull ajax request
So Iwould like to know why the return type is still array and not JSON since a new conversion has been made when the ajax request succeed
The reason is because how you are setting up your array before encoding it.
$arrays[] = $data;
PHP will set it as an object if the depth of the elements go beyond just an array of arrays.
Example:
If you create a simple 2d array like this one:
$p = [
'name' => 'jack',
'job' => 'ceo',
'age' => 'old'
]; // {"name":"jack","job":"ceo","age":"old"}
You will have an Object in your JS code; That's because of the way PHP handles it. However, look at this example as an alternative: This will return an array of objects:
$p = [[
'name' => 'jack',
'job' => 'ceo',
'age' => 'old'
],[
'name' => 'sam',
'job' => 'cool',
'age' => 'decent'
]];
echo json_encode($p); //[{"name":"jack","job":"ceo","age":"old"},{"name":"sam","job":"cool","age":"decent"}]
It's all about that key placement. If you have a key => pair array it will become an Object no matter what. Look at another example of a simple JS array:
print_r(json_encode([
'burger',
'pizza'
])); // ["burger","pizza"]
But if you add just one key=>pair to your array it will become an json object:
print_r(json_encode([
'burger',
'pizza',
'people' => [
'jack' ,
'sam',
'pete'
]
])); // {"0":"burger","1":"pizza","people":["jack","sam","pete"]}
Just for educational purpose if you throw it inside another 1d array you will get an array objects:
print_r(json_encode([[
'burger',
'pizza',
'people' => [
'jack' ,
'sam',
'pete'
]
]])); // [{"0":"burger","1":"pizza","people":["jack","sam","pete"]}]
Explanation:
When dealing with an array, it will strictly handle it's key from 0 to however many items are in the array; so an array in json_encode terms is anything with a simple 1d interface:
Which in PHP & JavaScript would look like this:
PHP
print_r([
'burger',
'pizza'
]); // Array ( [0] => burger [1] => pizza )
Javascript
console.log([
'burger',
'pizza'
]); // Array [ "burger", "pizza" ]
When adding the key to your array and making it into a 2d or more complex json_encode will convert it to a JavaScript Object; as we saw in the first example:
I'm making an app in Nodejs using express and node-xlsx module, what I want to do is to make the user able to upload an xlsx file (which has to have an specific format of two columns), an then the server reads it and does something with each row of the file.
(Example of my test file, being the columns A and B respectively):
Johny Wilson | jonhny#email.com
Andrew Jehnsen | andrew#example.com
Billy Soon | billy#mail.com
In order to do this, I've decided to use the node-xlsx module, which, after reading the file with this code:
var xlsx = require('node-xlsx');
router.post('/enviar', upload.single("lista"),(req, res, next) =>{
//dir is the path of the xlsx file
const workSheetsFromFile = xlsx.parse(dir);
res.send(workSheetsFromFile);
});
returns an object that looks like this:
[
{
"name": "Hoja1",
"data": [
[
"Johny Wilson",
"jonhny#email.com"
],
[
"Andrew Jehnsen",
"andrew#example.com"
],
[
"Billy Soon",
"billy#mail.com"
]
]
}
]
As you can see, the module returns the data of all the file, including the sheet's details (In this case only one), I want to access only to the 'data' array which contains keys and values to process them.
I've already tried to loop on the data array with:
workSheetsFromFile.data.forEach((element) =>{
console.log(element);
});
and
workSheetsFromFile[data].forEach((element) =>{
console.log(element);
});
and
workSheetsFromFile['data'].forEach((element) =>{
console.log(element);
});
but all of them just send me an error like "Cannot read property 'forEach' of undefined" or "data is not defined" :(
For now, with those few lines of code I was specting to iterate the data array and print each pair of key and value, so once that is fixed, inside this loop process each key and value in order to send automated mails.
What you have here seems to be an array of objects, not an object itself!
try
workSheetsFromFile[0].data.forEach((element) => {
console.log(element);
});
If you have more elements, consider first looping the array and then extracting data
const structuredData = workSheetsFromFile[0].data.map(res => {
return res
});
workSheetsFromFile.forEach(sheet => {
//access data
console.log(sheet.data)
//or
sheet.data.forEach(data => {
//access each data
console.log(data)
})
})
I have the following javascript that sends data to a PHP function:
<script>
var mydata = {
id:123,
name: 'mike',
orders: []
};
$.ajax({
type: 'POST',
url: 'test.php',
data: {save_data:mydata},
success: function(data) {
alert('php received: ' + data);
}
});
</script>
and my test.php file contains the following code:
<?php
if (isset($_POST['save_data'])) {
$json = json_encode($_POST['save_data']);
echo $json; // just to check what has been received
exit();
}
?>
What I expect to received from PHP is:
{"id":"123","name":"mike","orders":"[]"}
What I got back is {"id":"123","name":"mike"}
Notice that orders array has been eliminated from the output. No place holder for it. I tried adding some dummy elements in the array, and that worked fine, and I received the array back with the elements.
I need PHP to receive the json object as is, even if it contains empty arrays.
How can I do that?
The JSON object is created inside PHP. Before then you just have form data.
jQuery will encode form data in a PHP-friendly style.
If you give it:
data: { foo: [1, 2, 3] }
It will convert that to:
foo[]=1&foo[]=2&foo[]=3
(although it will percent encode the [])
You get a key=value pair for each value.
If you have an empty array then you don't have any values, so you don't get any key=value pairs.
There is no way to encode "an empty array" using PHP's extensions to the form url encoding syntax.
You have two basic options:
Tell PHP about what data structure you want to create in advance and have it fill in the empty arrays.
Generate the JSON on the client
It is not error of PHP. It cause by Jquery will igrone empty array when send it to server. So you have to parse array in 'orders' key to string JSON before send
var mydata = {
id:123,
name: 'mike',
orders: []
};
Change to
var mydata = {
id:123,
name: 'mike',
orders: JSON.stringify([])
};
I have a feeling this is a total noob question but I wasn't able to find any information so here goes.
I need to "translate" php data model objects to JavaScript data model objects for a node.js project. I am pretty new to node.js and I simply don't understand the syntax of the data model objects.
Here's the barebones template that was provided (user.js):
'use strict';
module.exports = function UserModel() {
return {
name: 'username'
};
};
Here's part of the php model I am working off of:
class Model_User extends Base_Model {
'name' => array(
'first' => 'first_name',
'last' => 'last_name',
),
'friends' => array(
'model' => 'User',
),
}
I have written ActionScript data model objects in the past and I thought JS would be mostly identical but in AS the data properties are declared as separate vars. Looking at the barebones template above, that doesn't seem to be the case for node.js JS data model objects.
What about:
var model = {
'name': [
{ 'first': 'first_name' },
{ 'last': 'last_name' }
],
'friends': [
{ 'model': 'User' }
]
};
This is basically creating a model object. It contains two key -> value pairs name & friends, which both contain arrays of objects.
Read this for more info on javascript objects: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects