How to make a JSON string into a javascript object. I am trying to convert the following string into JSON Object like this that is getting from the server
JSON String:
["{"title":"Admin Dhaka","href":"#0","dataAttrs":[],"data":["{\"title\":\"BNS HAJI MOHSIN\",\"href\":\"#0\",\"dataAttrs\":[\"{\\\"title\\\":\\\"id\\\",\\\"data\\\":\\\"51\\\"}\"]}","{\"title\":\"BNS ISSA KHAN\",\"href\":\"#1\",\"dataAttrs\":[\"{\\\"title\\\":\\\"id\\\",\\\"data\\\":\\\"1\\\"}\"]}","{\"title\":\"BNT KHADEM\",\"href\":\"#2\",\"dataAttrs\":[\"{\\\"title\\\":\\\"id\\\",\\\"data\\\":\\\"6\\\"}\"]}","{\"title\":\"BN DOCKYARD\",\"href\":\"#3\",\"dataAttrs\":[\"{\\\"title\\\":\\\"id\\\",\\\"data\\\":\\\"13\\\"}\"]}","{\"title\":\"BNT SEBAK\",\"href\":\"#4\",\"dataAttrs\":[\"{\\\"title\\\":\\\"id\\\",\\\"data\\\":\\\"7\\\"}\"]}","{\"title\":\"Naval Aviation\",\"href\":\"#5\",\"dataAttrs\":[\"{\\\"title\\\":\\\"id\\\",\\\"data\\\":\\\"89\\\"}\"]}","{\"title\":\"BNS SAIKAT\",\"href\":\"#6\",\"dataAttrs\":[\"{\\\"title\\\":\\\"id\\\",\\\"data\\\":\\\"40\\\"}\"]}","{\"title\":\"BNS Novojatra\",\"href\":\"#9\",\"dataAttrs\":[\"{\\\"title\\\":\\\"id\\\",\\\"data\\\":\\\"119\\\"}\"]}","{\"title\":\"BNS SHAH AMANAT\",\"href\":\"#10\",\"dataAttrs\":[\"{\\\"title\\\":\\\"id\\\",\\\"data\\\":\\\"11\\\"}\"]}"]}"]
As an example, I have given one object in the above code actually the Array is a list of Objects like this
[obj1, obj2....]
I tryed as follows:
var arr = '<?php echo !empty($treeView) ? $treeView : "[]"; ?>';
arr = JSON.parse(arr);
console.log(arr);
Getting the following error:
Uncaught SyntaxError: Unexpected token t in JSON at position 4
PHP Code:
function ship_by_area_zone(){
$area_list = [];
$ship_list = [];
$zone = $this->utilities->findAllByAttributeWithOrderBy("bn_navyadminhierarchy", array("ADMIN_TYPE" => 1, "ACTIVE_STATUS" => 1), "CODE");
$area = $this->utilities->findAllByAttributeWithOrderBy("bn_navyadminhierarchy", array("ADMIN_TYPE" => 2, "ACTIVE_STATUS" => 1), "CODE");
// area wise ship
foreach ($area as $key=>$value)
{
$row = $this->db->query("select * from bn_ship_establishment where AREA_ID = $value->ADMIN_ID and ACTIVE_STATUS = 1 order by CODE asc")->row();
if($row)
{
$dataAttrs = array();
$dataAttrs['title'] = 'id';
$dataAttrs['data'] = $row->SHIP_ESTABLISHMENTID;
$dataAttrs = json_encode($dataAttrs);
$ship_row = array();
$ship_row['title'] = $row->NAME;
$ship_row['href'] = "#$key"; //"#1"
$ship_row['dataAttrs'] = [$dataAttrs];
$ship_list[] = json_encode($ship_row);
}
}
// zone wise area
foreach ($zone as $key=>$value)
{
$row = $this->db->query("select * from bn_navyadminhierarchy where ACTIVE_STATUS = 1 and PARENT_ID = $value->ADMIN_ID order by CODE asc")->row();
if($row)
{
$area_row = array();
$area_row['title'] = $row->NAME;
$area_row['href'] = "#$key";
$area_row['dataAttrs'] = [];
$area_row['data'] = $ship_list;
$area_list[] = json_encode($area_row);
}
}
return json_encode($area_list);
}
Can anyone help me?
Thanks in advance!
You need to use json_encode in your PHP:
var arr = '<?php echo json_encode(!empty($treeView) ? $treeView : "[]"); ?>';
First of all, the json string you have there is invalid. You can check free online to validate the json. Once you have a valid json, you can use JSON.parse() to convert it to JSONObject
// converting a simple javascript object to JSON object
my_details =
{
"name" : "SL",
"age " : "30" ,
"photo" : "imgMe.jpg"
}
my_details_in_json = JSON.stringify(my_details);
// "{"name":"SL","age ":"30","photo":"imgMe.jpg"}" --> my_details_in_json
Related
So, I've looked through similar questions out here, but still couldn't find an answer to my query.
For some reason, I seem to get "undefined values along with my actual values in my json object. I receive these values from my php file. The code ffor the php file is as follows:
$sql = "SELECT distinct rackID FROM rackusage where startTime like '%".$curdate."%'";
$res = mysql_query($sql);
while($r = mysql_fetch_assoc($res)){
// Queries to get respective values to put inside my array
$temp[] = array('id' => (int) $r['rackID']);
$temp[] = array('rackName' => (string) $rackname);
$temp[] = array('uptime' => (int) $uptime);
$temp[] = array('downtime' => (int) $downtime);
$temp[] = array('utilization' => (int) $utilization);
} echo json_encode($temp);
The output string is as follows:
[{"id":1},{"rackName":"xyz"},{"uptime":119},{"downtime":0},{"utilization":0},{"id":2},{"rackName":"abc"},{"uptime":122},{"downtime":0},{"utilization":0},{"id":3},{"rackName":"pqr"},{"uptime":114},{"downtime":0},{"utilization":0}]
The JS code is:
function workwithdate(curdate){
$.ajax({
type: "Post",
url: 'senddata.php',
data:{'selectDate': curdate},
async: false,
success: function(data){
if(data){
alert(data);
recData= $.parseJSON(data);
//recData = data;
console.log(recData);
alert(recData);
alert(recData.length);
$.each(recData, function(idx, la){
var someid = la.id;
console.log(someid);
var rName = la.rackName;
console.log(rName);
var rUptime = la.uptime;
console.log(rUptime);
});
}
}
});
}
My output looks like this:
TIA
You want one associative array per row, so:
while($r = mysql_fetch_assoc($res)){
$temp[] = array(
'id' => (int) $r['rackID'],
'rackName' => (string) $rackname,
'uptime' => (int) $uptime,
'downtime' => (int) $downtime,
'utilization' => (int) $utilization
);
}
I have this array value: print_r ($array); which contains 2 data (this is latt and long of my gmap project).
The array is from:
<?php
if(isset($_GET['q'])) {
$q = $_GET['q'];
}
$q = isset($_GET['q']) ? $_GET['q'] : '';
$array = array();
$nsUser="SELECT * FROM cliententry WHERE kampusterdekat=:q";
$uQuery = $mydb->prepare ($nsUser);
$uQuery->execute(array(':q' => $q));
while ($result = $uQuery->fetch(PDO::FETCH_ASSOC)) {
$id=$result['id'];
$googlemap=$result['googlemap'];
//echo $googlemap;
$array[] = $googlemap;
print_r ($array);
}
?>
When I echo, the result will be like this:
Array
(
[0] => -5.364000343425874, 105.24465411901474
)
Array
(
[0] => -5.364000343425874, 105.24465411901474
[1] => -5.362878747789552, 105.24150252342224
)
Point:
What I need is to make the result into this format:
var wwwsitus = [
['<h4>area</h4>', wwwsitus[0]],
['<h4>area</h4>', wwwsitus[1]],
];
where locations (<h4>area</h4>) are removed. So, it must be, as follows:
var wwwsitus = [
[...,...],
[...,....],
];
Note:
Since I've no capable about array in JS, please help me to fix my title based on my issue. Thks in adv.
Good day,
I have this data which I got from my query on PHP its is currently a JSON Format, now I want to convert it into array so I can use it on my pdf. How can I do this?
so in order for me to use it on my javascript I used
var inventory = <?php echo json_encode($inventory); ?> ;
my JSON data :
var inv = [
{"xid":96,"xitem":"CARBOCISTEINE 500MG CAP (MYREX) BOX",
"itemId":852,
"price":3,
"mprice":3
},
{"xid":253,"xitem":"CIPROFLOXACIN 500MG TAB (PROSELOC\/FLAMINGO)",
"itemId":1165,
"price":0,
"mprice":0
}];
I tried
var rows = <?php echo json_encode($inventory); ?> ;
var arr = $.map(rows, function(el) { return el; });
and
when I console.log(arr);
I still get the object structure not the array structure that I wanted.
I also tried
var result = [];
for(var i in rows)
result.push([i, rows [i]]);
console.log(result);
but it gives me
[ ["0",Object { xid=96,xitem="CARBOCISTEINE 500MG CAP (MYREX) BOX",itemId=852,price=3,mprice=3}],
["1",Object{etc..}]];
instead
I want it to have a structure like
[96,"CARBOCISTEINE 500MG CAP (MYREX) BOX",852,3,3],
[253,"CIPROFLOXACIN 500MG TAB (PROSELOC\/FLAMINGO)",1165,0,0]
Is there something I am missing on my code or How should I be able to do this? thanks..
You can use this:
var arr = inv.map(function (obj) { return [obj.xid, obj.xitem, obj.itemId, obj.price, obj.mprice]})
console.log(arr);
If you do small changes to your map callback function, then it will be fine.
you can do just
class MyClass
{
public $var1 = 'value 1';
public $var2 = 'value 2';
public $var3 = 'value 3';
}
$class = new MyClass();
$arr = [];
foreach($class as $key => $value) {
$arr[] = $value;
}
echo json_encode($arr); //here's to check
in PHP - you can make a collection of object like this and iterate first oveer this collection to get result as you wanted to have
You shouldn't have to hard code the keys. The following works:
var arrayFromObject = inv.map(function (item) {
var arr = [];
for (var p in item) arr.push(item[p])
return arr;
});
I've looked through various other questions on SO, but can't quite get the right answer. Basically, I have an array that needs data from a MySql database. Here's what I've tried:
var $name = "Foo",
$x = 10,
$bar =
<? php
$barQuery = mysql_query("SELECT item FROM table WHERE name = '$name' AND number = '$x'");
$barArray = array();
while ($r = mysql_fetch_assoc($barQuery))
{
$barArray[] = $r['item'];
}
echo json_encode($barArray);
?>;
EDIT: I then post this to a .php file, and print the returned data:
$.post("file.php", {bar: JSON.stringify($bar), name: $name}).done(function(data)
{
$('body').html(data);
window.print();
setTimeout("location.reload(true)", 500);
});
However, I get an error saying "syntax error, unexpected T_VARIABLE". Is it not possible to populate a JS array this way, or is there another way to do it?
var $name = "Foo",
$x = 10,
$bar = "
<?php
$barQuery = mysql_query("SELECT item FROM table WHERE name = '$name' AND number = '$x'");
$barArray = array();
while ($r = mysql_fetch_assoc($barQuery))
{
$barArray[] = $r['item'];
}
echo json_encode($barArray);
?>";
You have a superfluous space inside the PHP opening tag:
<? php
^--- this shouldn't be there
As it stands, the <? is parsed as a short open tag, and so the php is parsed as a(n undefined) constant, which is immediately followed by $barQuery—hence the syntax error that you see: unexpected T_VARIABLE.
I have fetched data from MySQL and echoed JSON encoded data as follows:
$result = mysql_query ("SELECT * FROM order_list");
$myjsons = array();
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
$myjsons[$i] = json_encode(array($row));
$i++;
}
echo json_encode($myjsons);
And I have a Javascript function that reads the string and shows it in a text box:
if(ajaxRequest.readyState == 4){
$.post('userfind.php', function(data) {
$("#txtfld").val(data);
var arr =data.slice(1);
var user_arr = arr.slice(0,-1);
var json = user_arr,
obj = JSON.parse(json);
alert(obj.user_id);
$("#resultTXT").val(obj.user_id);
},'json'
);}
}
ajaxRequest.open("POST", "userfind.php", true);
ajaxRequest.send(null);
}
The problem is that txtfld shows the string as [{"user_id":"2790","fre.....tst":""}] and resultTXT shows nothing because of the two [ ]. I have tried to remove them using slice but it seems that the slice doesn't work on JSON strings. What else can I do to remove [ ] so that the resultTXT shows the user_id?
Thanks
you convert the array 2 times to json.
php doesn't need the a index for the next array element
i would also add the correct header "application/json"
$row is already a associative array
$result = mysql_query ("SELECT * FROM order_list");
$myjsons = array();
while ($row = mysql_fetch_assoc($result)) {
$myjsons[] = $row;
}
header('Content-type: application/json');
echo json_encode($myjsons);
this gives you a proper formatted json
to access your json in javascript u do:
var obj=JSON.parse(json);
i assume that your mysql returns a list of orders or users [{"user_id":1},{"user_id":2}] so if you want to access the first user's id:
obj[0].user_id
but if i misunderstand u could post more info about your json.