In practice, I create an array in PHP that then I pass to a JavaScript function.
So far so good. The array that the functions recieves is the following:
[[{"firstname": "Micheal", "lastname": "Brown"}], [{"car": "Ford", "model": "Fiesta"}]]
My problem is to get all the first array, that is this: {"firstname": "Micheal", "lastname": "Brown"}
and also the second array this: {"car": "Ford", "model": "Fiesta"}
I tried with alert (array [0]) but it only shows me this [
How can I do this?
I'll explain:
this is my php file:
class UserClasses
{
public $firstname;
public $lastname;
}
class CarClasses
{
public $car;
public $model;
}
if(isset($_POST['name'])){
populate($_POST['name']);
}
function populate(){
//I abbreviated the function for simplicity
$arrayUser = array();
$arrayCar = array();
$user = new UserClasses();
$user->firstname = "Micheal";
$user->lastname = "Brown";
array_push($arrayUser, $user);
$car = new CarClasses();
$car->car = "Ford";
$car->model = "Fiesta";
array_push($arrayCar, $car);
$arrayFinal = array($arrayUser, $arrayCar);
print json_encode($arrayFinal);
}
and this is the function in javascript:
//Ajax for calling php function
$.post('Classes.php', { name: name }, function(data){
var array = JSON.parse(data);
var arrayT = array[0];
alert(arrayT);
});
Here's what is happening with your code: you're accessing the first element of a JSON string, so my guess is you will get its first character: [.
You need to convert your string into an actual array before accessing it!
Use JSON.parse:
The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string.
- MDN web docs
For example you can do:
const json = '[[{"firstname": "Micheal", "lastname": "Brown"}], [{"car": "Ford", "model": "Fiesta"}]]'
// that's what you have
console.log(json[0])
// that's what you want
array = JSON.parse(json)
console.log(array[0])
First of all, if you are using json_encode to pass PHP array to JS, it encodes it to a JSON string. You have to parse it using JSON.parse() and only then the json string is transformed to regular array which you can use.
You can parse data and use it:
var arr = '<?php echo '[[{"firstname": "Micheal", "lastname": "Brown"}], [{"car": "Ford", "model": "Fiesta"}]]'; ?>';
var parsedarr = JSON.parse(arr);
for(var i=0;i<parsedarr.length;i++){
console.log(parsedarr[i][0]);
}
You are dealing with 3 different Data Types:
a PHP Multidimensional Array
a JSON String
a Javascript Object
Each needs to be converted into the next.
A PHP Array is converted into a JSON String, via json_encode() (in PHP)
A JSON String is converted into a Javascript Object, via JSON.parse() (in Javascript)
Now you have a Javascript Object which you can interrogate and manipulate using Javascript.
PHP Multidimensional Array:
$My_PHP_Array = array(
array(
'firstname' => 'Michael'
'lastname' => 'Brown'
),
array(
'car' => 'Ford'
'model' => 'Fiesta'
)
);
Convert PHP Multidimensional Array to JSON String:
json_encode($My_PHP_Array);
JSON String:
'{
[
[{
"firstname": "Micheal",
"lastname": "Brown"
}],
[{
"car": "Ford",
"model": "Fiesta"
}]
]
}'
Convert JSON String to Javascript Object:
var myJavascriptObject = JSON.parse(myJSONString);
Javascript Object:
myJavascriptObject = {
[
[{
"firstname": "Micheal",
"lastname": "Brown"
}],
[{
"car": "Ford",
"model": "Fiesta"
}]
]
};
Related
I have the following object below with multiple arrays.
{
"services": [
{
"id": "100",
"name": "PIX"
},
{
"id": "200",
"name": "Rendimentos"
}
],
"channels": [
{
"id": "300",
"name": "Chat"
}
]
}
The idea is to generate query strings, something like that.
services=100&services=200&channels=300
I know you can do it with map and join, but I would know if it was with a pure object, now this format below, I'm confused
You can use URLSearchParams() API.
Iterate your data and append key/value pairs or map an entries array to pass to the constructor
I have no idea what determines the expected output you have shown from the data displayed so am using a simpler data structure for demonstration purposes.
You can combine with URL() API to create full url string as shown below also
const data = [
{name:'foo', value:10},
{name:'bar', value:20}
]
// Loop and append key/values
const params = new URLSearchParams();
data.forEach(e => params.append(e.name, e.value));
console.log('params:', params.toString());
// Alternate approach passing entries array to constructor
const params2 = new URLSearchParams(data.map(e => [e.name,e.value]));
console.log('params2:',params2.toString())
//Adding to a URL
const url = new URL('http://example.com')
url.search = params
console.log('Full url:',url)
Using the updated array data in question:
const data={services:[{id:"100",name:"PIX"},{id:"200",name:"Rendimentos"}],channels:[{id:"300",name:"Chat"}]};
const entries = [];
Object.entries(data).forEach(([k,arr])=> arr.forEach(({id}) => entries.push([k,id])));
const params = new URLSearchParams(entries);
const url = new URL('http://example.com')
url.search = params;
console.log(url)
Looks like you're hung up on trying to iterate an object with map() or join(), which you can't do directly. Instead you can use Object.entries to convert the object into an array and iterate that. Since there is a nested map() you can flat() it before join()
let obj = {
"services": [{
"id": "100",
"name": "PIX"
},
{
"id": "200",
"name": "Rendimentos"
}
],
"channels": [{
"id": "300",
"name": "Chat"
}]
}
let queryString = Object.entries(obj).map(s => s[1].map(e => `${s[0]}=${e.id}`)).flat().join('&')
console.log(queryString)
I've a php query which creates the JSON data of the the data received from the SQL query that is run. The JSON data is created using this query using this query
echo json_encode($res->fetch_all(MYSQLI_ASSOC), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT );
Now I want to plot a chart using fusionchart for which I need to convert this data into an array. I tried a sample JS code to convert the JSON data into an JS array and it worked
var data = { "timestamp": "2016-09-23", "value1": "0", "value2": "0", ........., "value49": "0", "value50": "0" };
var arr = [];
for (elem in data) {
arr.push(data[elem]);
}
console.log(arr);
Now in the data variable I need to pass the data from php code. This is just one of the records that I entered manually. There are over a million records and I need to convert all of them. How I do this?
You can use parseJSON() function :
var obj = jQuery.parseJSON( '{ "name": "John" }' );
alert( obj.name === "John" );
You can just use Object.values() function to acquire values from an object.
var data = { "timestamp": "2016-09-23", "value1": "0", "value2": "0", "value49": "0", "value50": "0" };
var arr = Object.values(data);
console.log(arr);
For PHP
You can send only values and omit keys in PHP using following code. json_decode converts JSON string to an array. implode converts an array to a string.
<?php
$str = '{ "timestamp": "2016-09-23", "value1": "val1",
"value2": "val2", "value49": "val49", "value50": "val50" }';
$myJSON = json_decode($str, true);
echo '[' . implode(",", $myJSON) . ']';
Results:
[2016-09-23,val1,val2,val49,val50]
I've json in this format :
[
{
"_id": {
"$oid": "560c079e1691682b4ff327ad"
},
"year": "2015",
"month": "9",
"day": "30",
"time": "17:02:17",
"problemDesc": "test",
"resolution": "test",
"IM": "test"
}
]
I'm attempting to access the year using : console.log(json[0].year) but receiving undefined. How to access the year value from this json string ?
fiddle :
http://jsfiddle.net/b8dggkof/
In the JSFiddle the value inside json is a string and not a JavaScript Object, you have to parse the string before try to access the value:
var json = JSON.parse('{"":[{"_id":{"$oid":"560c079e1691682b4ff327ad"},"year":"2015","month":"9","day":"30","time":"17:02:17","problemDesc":"test","resolution":"test","IM":"test"}]}');
console.log(json[''][0].year);
After you parsed the string, you need to access the object with key an empty string:
json['']
The value associated to this key is an array and you need the first element, so:
json[''][0]
Now you can get the year:
json[''][0].year
You need to put in a key for the JSON and then access by the key the inner Object, after you parse it since it is a string enclosed in quotes '
var json = '{"key":[{"_id":{"$oid":"560c079e1691682b4ff327ad"},"year":"2015","month":"9","day":"30","time":"17:02:17","problemDesc":"test","resolution":"test","IM":"test"}]}'
console.log(JSON.parse(json)['key'][0].year);
you need to parse you json string to json object by using JSON.parse then use key name in you case which is ''(empty string)
var jsonStr = '{"":[{"_id":{"$oid":"560c079e1691682b4ff327ad"},"year":"2015","month":"9","day":"30","time":"17:02:17","problemDesc":"test","resolution":"test","IM":"test"}]}';
var parseJson = JSON.parse(jsonStr);
alert(parseJson[''][0].year)
How modified this function to add every object in file's new line?
exports.addWaypoint = function(id, type, param){
var dataIn = fs.readFileSync('./markers.json');
var obj = JSON.parse(dataIn);
obj.markers.push({
"id": id,
"type": type,
"param": param,
});
writeJson(obj);
}
This may be a duplicate of Javascript: How to generate formatted easy-to-read JSON straight from an object?
Here's a quick answer: use JSON.stringify with an optional parameter to indicate the indention for each nested element.
var o = {
"id": 123,
"type": "good",
"param": { name: "Fred", age: 24 },
};
console.log( JSON.stringify(o,null,4) );
Can a JSON array contain Objects of different key/value pairs. From this tutorial, the example given for JSON array consists of Objects of the same key/value pair:
{
"example": [
{
"firstName": "John",
"lastName": "Doe"
},
{
"firstName": "Anna",
"lastName": "Smith"
},
{
"firstName": "Peter",
"lastName": "Jones"
}
]
}
If I want to change it to have different key/value pairs inside the JSON array, is the following still a valid JSON?
{
"example": [
{
"firstName": "John",
"lastName": "Doe"
},
{
"fruit": "apple"
},
{
"length": 100,
"width": 60,
"height": 30
}
]
}
Just want to confirm this. If so, how can I use JavaScript to know if the JSON "example" field contains the first homogeneous objects or the second heterogeneous objects?
You can use any structure you like. JSON is not schema based in the way XML is often used and Javascript is not statically typed.
you can convert your JSON to a JS object using JSON.parse and then just test the existence of the property
var obj = JSON.parse(jsonString);
if(typeof obj.example[0].firstName != "undefined") {
//do something
}
It doesn't matter you can mix and match as much as you want.
You could just test it
typeof someItem.example !== 'undefined' // True if `example` is defined.
It's perfectly valid JSON. Personally I prefer this syntax better, because it reads easier:
{
"example": [
{
"firstName": "John",
"lastName": "Doe"
},
{
"fruit": "apple"
},
{
"length": 100,
"width": 60,
"height": 30
}
]
}
As to answer your second question, you can read data from a JSON string by using var data = JSON.parse(datastring);. Then simply use it by calling data.property.secondlevel. Any variable can be an object, array, string or number, allowing for nested structures.
You are free to do what you want with the contents of the array. Jus remember about this before you try to iterate an access properties of each item in your array.
one thing: you won't be able to deserialize this to anything else than an array of object in your server side, so don't have surprises later.
as a hint, maybe you could include a common field in the objects specifying the "type" so later is easy to process.
var array = [{"type":"fruit", "color":"red"},
{"type":"dog", "name":"Harry"}];
var parser = {
fruit:function(f){
console.log("fruit:" + f.color);
},
dog: function(d){
console.log("dog:"+d.name);
}};
for(var i=0;i<array.length;i++){
parser[array[i].type](array[i]);
}