Adding a new associative element to a JSON object - javascript

i have the problem to add elements to an json array.
The structure i want is that:
[{"method":"edit","type":"1", "template":"3", "meta":{"title":"Tools", "descirption":"Tools"}}]
The problem is that i add all these parameters dynamically.
So lets say i have for the start:
[{"method":"edit","type":"1", "template":"3"}]
How can i add the whole "meta" array and please do not be with push(), because than i will have another structure when i print it.
When i use
$json = json_decode($json, true);
I want to have:
array(
method' => edit,
'type' => 1,
'template' => 3,
'meta' => array('title' => '')
);
Thanks in advice !

So I'm going to assume you have the JSON to start with. So let's decode to PHP (as you noted correctly)
$json = json_decode($json, true);
So now we should have $json['method'], etc. Now let's define $meta
$meta = array('title' => '');
And add this to $json
$json['meta'] = $meta;
echo json_encode($json);

When your current JSON decodes in PHP using json_decode, it will decode into an array with one element, or array[0]. Therefore in order to access or any object you need to first point to that 0 index. Do it this way:
$json = '[{"method":"edit","type":"1", "template":"3"}]';
$arr = json_decode($json);
$arr[0]->meta = array('title' => '');
$json = json_encode($arr);
var_dump($json);
//Result:
// string '[{"method":"edit","type":"1","template":"3","meta":{"title":""}}]' (length=65)

Related

converting data from sqlite PHP

I have a number of coordinates stored in a sqlite database. I need these coordinates to be used in a heatmap on leaflet.
I'm using the following plugin: https://github.com/Leaflet/Leaflet.heat
The data needs to be in the following format:
var addressPoints = [
[52.344161, 4.912279],
[52.342425, 4.913038],
[52.342034, 4.913256],
[52.341987, 4.912462]];
I extract the data from the sqlite database in PHP using:
$db = new SQLite3('jwtrack.sqlite');
$results = $db->query("SELECT coord FROM trackjw");
while ($row = $results->fetchArray()) {
echo json_encode($row['coord']);
}
$db->close();
The data retrieved looks like:
"52.344161000, 4.912279000""52.342425000, 4.913038200""52.342034000, 4.913256000""52.341987000, 4.912462000""52.342336000, 4.912106000"
How can I get the SQLite data inserted in 'var addressPoints' in a correct manner?
Thansk in advance,
JWB
If the data follows that same format with the quotes at start and end and double quotes in between pairs the following should produce an array with the pair as an entry.
$data='"52.344161000, 4.912279000""52.342425000, 4.913038200""52.342034000, 4.913256000""52.341987000, 4.912462000""52.342336000, 4.912106000"';
$pairs=explode('""',trim($data,'"'));
print_r($pairs);
output:
Array
(
[0] => 52.344161000, 4.912279000
[1] => 52.342425000, 4.913038200
[2] => 52.342034000, 4.913256000
[3] => 52.341987000, 4.912462000
[4] => 52.342336000, 4.912106000
)
You could alter your initial php however which would produce different data
$db = new SQLite3('jwtrack.sqlite');
$results = $db->query("SELECT coord FROM trackjw");
$json=array();
while( $row = $results->fetchArray() ) {
$json[]=$row['coord'];
}
$db->close();
$json=json_encode( $json );
echo $json;
if you needed this without the quotes around the values...
$json=str_replace('"','',$json);
in the javascript then you could do:
echo "var addressPoints={$json};";

Getting PHP array through AJAX

I want to create comments with AJAX, I do not know if this is the right way its my first time doing it. I have been searching google for hours and im really stuck.
What I want to achieve is to add a comment right after I click 'comment' button wihtout reloading the page.
I do not know how to create JSON array that will suit my needs.
This is my javascript:
$(function(){
var userComments = $('.userComments');
var commentsUrl="commentsLoad.php";
$.ajax({
type: 'GET',
url: commentsUrl,
dataType: "json",
success: function(komentarji){
//$.each ...
userComments.append("output...");
},
error: function(e){
console.log(e);
}
});
});
This is my PHP:
include('config.php');
$comments=array();
$commentsQuery = "SELECT * FROM komentarji";
$result = $conn->query($commentsQuery);
if($result->num_rows>0){
while($row = $result->fetch_assoc()){
$comments=array(
'id' => $row['id'],
'name' => $row['name'],
'text' => $row['text'],
'date' => $row['date'])
);
header('Content-type: application/json');
echo json_encode($comments);
}
}
The path that you're on is almost perfectly paved. Except the following you need to take note of:
You should echo the result array in the JSON format outside the while loop.
Since you have specified the dataType as json in your ajax call (and telling jQuery that you are expecting json back from the server), $.ajax will handle the headers itself and therefore header('Content-type: application/json'); is not needed.
A little tweak on the assignment that you're doing on $comments array:
$comments[] = array( // without [] you'll always end up with ONE comment
'id' => $row['id'],
'name' => $row['name'],
'text' => $row['text'],
'date' => $row['date']
);
Just as you have hinted subtly, you need to iterate the returned array and append each comment one-by-one:
success: function(komentarji){
var parsedComments = JSON.parse(komentarji); //parse the result to Javascript readable objects
$.each(parsedComments, function(){
userComments.append("id =>" + this.id + " name => " + this.name + " text =>" + this.text /* etc. */); //you can access each column key as javascript object key here
});
}, //...
Note: There is a typo in the array assignment that you're doing, just remove the ) on the line 'date' => $row['date']) and you'll be fine.
First of all, move the returning of data back to the javascript code out of the while loop so you only do it once. Then change the script a little so that each comment is added to a new occurrence in the $comments array.
include('config.php');
$comments=array();
$commentsQuery = "SELECT * FROM komentarji";
$result = $conn->query($commentsQuery);
if($result->num_rows>0){
while($row = $result->fetch_assoc()){
$comments[] = array(
'id' => $row['id'],
'name' => $row['name'],
'text' => $row['text'],
'date' => $row['date'])
);
}
}
echo json_encode($comments);
exit;
You can't send more than one json output but you are sending one in each iteration of while loop
Also can't keep adding header
what you will be sending will look like
{"id": 3 , "name": "foo"}
{"id": 4 , "name": "bar"}
Note that there is no outer array wrapping these or comma separating them.
Thus they are invalid json when sent together.
Put all the comments into one array and send that instead
Try this:
include('config.php');
$comments = array();
$commentsQuery = "SELECT * FROM komentarji";
$result = $conn->query($commentsQuery);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
array_push($comments, array('id' => $row['id'], 'name' => $row['name'], 'text' => $row['text'], 'date' => $row['date']));
}
return json_encode(array('status' => true, 'data' => $comments));
} else {
return json_encode(array('status' => false));
}
Also return status with response so that it will be easier to manipulate response

strange behavior json_decode

I'm creating a json in javascript in that way
jsonArr.push({
position: 'WN',
wind: windWN,
wave: waveWN,
sea: seaWN
});
var myJsonString = JSON.stringify(jsonArr);
I'm sending it via an AJAX method with jsonData: jsonData:Ext.encode(myJsonString)
My json array looks like that when I send it :
In PHP side, I'm getting the Json and decoding it that way :
$rawpostdata = file_get_contents("php://input");
$rawpostdata2 = json_decode($rawpostdata, true);
I tried print_r( $rawpostdata2[1]); and got '{', as the second character of the "string", and I can't understand why.
In the other side, I tried print_r($rawpostdata), cut/past the result in a $string and retest my json_decode like that :
$rawpostdata = file_get_contents("php://input");
// print_r($rawpostdata);
$string = '[{"position":"N","wind":"2","wave":"65","sea":"65"},{"position":"E","wind":"3","wave":"5","sea":"6"},{"position":"S","wind":"56","wave":"4","sea":"8"},{"position":"W","wind":"1","wave":"56","sea":"84"},{"position":"NE","wind":"5","wave":"6","sea":"65"},{"position":"ES","wind":"6","wave":"45","sea":"6"},{"position":"SW","wind":"69","wave":"8","sea":"4"},{"position":"WN","wind":"7","wave":"8","sea":"56"}]';
$rawpostdata2 = json_decode($string,true);
print_r ($rawpostdata2[1]);
It gives me the correct result !
Array (
[position] => E
[wind] => 3
[wave] => 5
[sea] => 6 )
Do you have some explanations?
EDIT : I make it working by making another json_decode
$rawpostdata = file_get_contents("php://input");
$rawpostdata2 = json_decode($rawpostdata,true);
$rawpostdata3 = json_decode($rawpostdata2,true);
But I don't really understand...
First, you create json string:
var myJsonString = JSON.stringify(jsonArr);
Then you encode the resulting string into json again:
Ext.encode(myJsonString)
Thus, you have to json_decode() twice in PHP.
Try using $_POST instead of file_get_contets() which gives you a string.
you need to do a type cast on the result of json_decode like this:
<?php
$rawpostdata = file_get_contents("php://input");
$rawpostdata2 = (array) json_decode($rawpostdata,true);
?>
I hope this works for you.. Cheers..!!

Echoing a series of JSON data from php to JavaScript,

I am having a difficulty retrieving a series of json data from php to my JavaScript, file..
Firstly, I have a series of json data stored in an array in php, and echoing each by wrapping it in the for loop to my JavaScript file,
<?php
$result = array('{"one": "test","two": "test"}','{"three": "test","four": "test"}');
for ($i = 0; $i < count($result); ++$i) {
echo $result[$i];
}
?>
in my JavaScript,
$.ajax({
url: "visualiser/visualiser_RouteList.php",
dataType: "JSON",
async: false,
success: function(data){
console.log(data);
}
});
My console does not display anything at all, not recognizing each array element as a json..
but if I send just one array element specifically, for example,
echo $result[0];
then it successfully displays,
Object {one: "test", two: "test"}
why can't I pass a series of json data in an array from php in my ajax call?
It doesn't work because you are generated malformed JSON. The output of your script is
{"one": "test","two": "test"}{"three": "test","four": "test"}
When you access the first element of the array only you get
{"one": "test","two": "test"}
Which is valid.
PHP has json_encode which will do this work for you, so your code would become
$result = array(
array('one' => 'test', 'two' => 'test'),
array('three' => 'test', 'four' =>'test')
);
echo json_encode($result);
giving the output
[{"one":"test","two":"test"},{"three":"test","four":"test"}]
Your code will output this:
{"one": "test","two": "test"}{"three": "test","four": "test"}
This is invalid JSON, so obviously will not work. (Try parsing it with JSON.parse and you'll see.)
You actually need to send the data as an array, so replace your for loop with a simple json_encode call:
echo json_encode($result);
This will output
[{"one": "test","two": "test"},{"three": "test","four": "test"}]
This is valid JSON, and can be parsed into a Javascript array.
Also can you this script
function doj($json){
$result = json_encode($json);
return json_decode($result, true);
}
$json = array(
'{"one": "test","two": "test"}',
'{"three": "test","four": "test"}'
);
$j = doj($json);
foreach($j as $k=>$v){
$extractagain = json_decode($v);
print_r($extractagain);
}
and the output is:
stdClass Object ( [one] => test [two] => test ) stdClass Object ( [three] => test [four] => test )

Converting data returned from mysql query to json(tree based)

This question has been asked earlier too, but no body has answered I guess.
Lets say mysql query returns result like following
name | id
tarun | 1
tarun | 2
tarun | 3
Now If we do standard json encode, I will get some thing like below:
[{"name":"tarun","id":"1"},{"name":"tarun","id":"2"},{"name":"tarun","id":"3"}]
But I was output something like below
[{"name" : "tarun", "ids" : [{"id": "1"},{"id": "2"},{"id": "3"}]}]
Please ignore my syntax mistakes (if any), But I hope my ques makes sense.
I am using PHP as my backend scripting language.
You're probably doing something like
SELECT name, id FROM ...
and
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
Given your desired structure, you'd want
$data[$row['name']]['ids'][] = array('id' => $row['id']);
This won't give you your exact structure, but it would be put all the ids as a child-array beneath an array keyed by the tarun field value.
Extending #Marc B's answer
// Getting per person id's list
$people = array();
while ($row = mysql_fetch_assoc($result)) {
$people[$row['name']][] = array('id' => $row['id']);
}
// Encoding as JSON
$output = "[";
foreach ($people as $name => $ids) {
$output .= '{"name" : "'.$name.'", ids: [';
foreach ($ids as $key => $id) {
$output .= '{"id" : "'.$id.'"},';
}
rtrim($output, ",");
$output .= ']},';
}
rtrim($output, ",");
$output .= ']';
echo $output;
The solution above is specific to the question. A generic JSON Encode method for this problem in my opinion is very tough or not possible.
I suggest to do the query with orderying by name, then when you read the rows, just do a simple check to see if the $row['name'] has changed, if so add the id's youve collected to the php object.
$curName="";
$curIds=array();
$betterJ=array();
$result = mysql_query ("SELECT name,id FROM mytable WHERE 1 ORDER BY NAME);
while($row=mysql_fetch_array($result)
{
if($curName=="")
$curName=$row['name']
if($row['name']!=$curName){
$betterJ[]=array($name=>$curName,$ids=>$Ids)
$curName=$row['name']
$curIds=array()
}
$Ids[]=$row['id];
}
$betterJ[]=array($name=>$curName,$ids=>$Ids);
echo json_encode($betterJ);
this might have a typo or something since I wrote it here, but it should produce json like
[ [name:"tarus1",ids:[1,2,3]], [name:"tarus2",ids:[4,5,6], ... ]
which you would work great in a template in html etc.

Categories