How to access json data in php? - javascript

I have complex json data. It can be in either formats as below :
1. {"Physics":{"5b87ceb691":"Motion","5b87ce3e":"Mass"}} //where value itself is a json
2. {"a60a8001805":"Finish chapter 1","a60a8002ab0":"Finish assignments"} //simple key value pair
I want to create checkboxes for all values (Motion, Mass, Finish chapter 1, Finish assignments for above examples) and keys should come like text in between those checkboxes (Physics for above example) (Key should come like text only if it's value is a json object, since Physics's value is a json, Physics should show like a text and in example 2, since there are no such keys whose value is a json object, no key will show like a text).
I've implemented this in javascript in the following way :
var str = "";
if(Object.keys(data).length !== 0) {
var i = 1;
for (var key in data) {
if (data.hasOwnProperty(key)) {
var val = data[key];
if(typeof val == 'object') {
str += '<div class = "data_text hidden">' + key + '</div>';
for (var subKey in val) {
if (val.hasOwnProperty(subKey)) {
var subValue = val[subKey];
str += '<div class="db-checkbox data_options hidden"><input type="checkbox" name="abc" id="' + i + '"><label for="' + i + '">' + subValue + '</label></div>'
i += 1;
}
}
} else {
str += '<div class="db-checkbox data_options hidden"><input type="checkbox" name="abc" id="' + i + '"><label for="' + i + '">' + val + '</label></div>'
i += 1;
}
}
}
Now, I want to do the same in php. I searched to find out the way to access json data in php, but all of those works only when keys are known. (For example, data->a60a8002ab0) But I want to do this generically. Don't want to hardcode anything. How can I do this? Thank you.

Try json_decode in associative mode by passing in the second param true so that it returns an associative array that you can loop through, similar to your javascript code.

//try each of the following by comment/uncomment
//$myjson = '{"Physics":{"5b87ceb691":"Motion","5b87ce3e":"Mass"}}';
//$myjson = '{"a60a8001805":"Finish chapter 1","a60a8002ab0":"Finish assignments"}';
$myjson = '{"a60a8001805":"Finish chapter 1","a60a8002ab0":"Finish assignments","Physics":{"5b87ceb691":"Motion","5b87ce3e":"Mass"}}';
$json_md_ary = json_decode($myjson,true);
$i=1;
foreach($json_md_ary as $key=>$val){
if (is_array($val)){
echo $key, "<br>";
foreach($val as $k=>$v){
echo $k, ' => ' ,$v,'<input type="checkbox" name="abc" id="'.$i.'">',"<br>";
$i++;
}
}else{
echo $key, ' => ' ,$val,'<input type="checkbox" name="abc" id="'.$i.'">',"<br>";
$i++;
}
}

$jsondata = '{"Physics":{"5b87ceb691":"Motion","5b87ce3e":"Mass"}}';
$data = json_decode($jsondata);
foreach($data as $key => $val){
print_r($val);
}

Related

objects, php, javascript errors

Javascript Object to a PHP Object
I was searching for the tutorial how to pass associative array from JavaScript to PHP object and found this video. I think it is a little bit old it was added in 2010. I tried it and had error. I ask you to help me to correct it or help me to to get php object from js object.
index.php
<script>
let ar = new Array();
ar["name"] = "name1";
ar["name1"] = "name2";
console.log(ar);
function convertOb(object){
var json = "{";
for (property in object) {
var value = object[property];
if (typeof(value) == "string") {
json += '"' + property + '":"' + value +'",';
} else{
if (!value[0]) {
json += '"' + property + '":"' + convertOb(value) + ',';
} else{
json+= '"'+ property +'":[';
for (prop in value) json+= '"' + value[prop] + '",';
json = json.substr(0,json.length-1) + "],";
}
}
} return json.substr(0,json.length-1) + "}";
}
let json = convertOb(ar);
$.post("main.php", {json:json}, function(data){
console.log(data);
});
</script>
main.php
<?php
function jsonstring2obj($str){
return json_decode(stripslashes($str));
}
$ar = jsonstring2obj($_POST['json']); //error1
echo $ar->name; //error2
?>
My errors:
Undefined index: json //error1
Trying to get property 'name' of non-object //error2

Uncaught SyntaxError: Unexpected token p in JSON at position 36

I´m populating webpage with sharepoint so I do a json to get data with ajax like these:
function completeFleet(data, target, eng) {
var items = data.d.results;
console.log(items);
var prefix = "<div class='row'>";
var sufix = "</div>";
var menu = "<div class='col-md-4'>";
var cat = "";
var spec = "";
var counter = 0;
var obj = null;
for (item in items) {
spec = "";
if (counter == 1) {
menu += "</div><div class='col-md-4'>";
counter = 0;
}
if (eng) {
obj = JSON.parse(items[item].Specifications);
for (var key in obj) {
spec += "<div class='row'><div class='col-md-12 ftBottomSeparator'><span class=' t10'>" + key + "</span> <span class='t06' style='float:right;'>" + obj[key] + "</span></div></div>";
}
menu += "<div class='row ftContainerOut'><div class='col-md-12 ftContainer'><div class='row ftHeader'><div class='col-xs-9 t09'>" + items[item].Title + "</div><div class='col-xs-3 text-right'></div></div><div class='row'><div class='col-md-6' style='padding-top:10px'><img src='" + items[item].Imagen.Url + "' class='img-responsive img-center' style='border:0px solid blue; max-width:150px;max-height:120px;' /></div><div class='col-md-6'>" + spec + "</div></div></div></div>";
} else {
obj = JSON.parse(items[item].Especificaciones);
for (var key in obj) {
spec += "<div class='row'><div class='col-md-12 ftBottomSeparator'><span class=' t10'>" + key + "</span> <span class='t06' style='float:right;'>" + obj[key] + "</span></div></div>";
}
menu += "<div class='row ftContainerOut'><div class='col-md-12 ftContainer'><div class='row ftHeader'><div class='col-xs-9 t09'>" + items[item].Title + "</div><div class='col-xs-3 text-right'></div></div><div class='row'><div class='col-md-6' style='padding-top:10px'><img src='" + items[item].Imagen.Url + "' class='img-responsive img-center' style='border:0px solid blue; max-width:150px;max-height:120px;' /></div><div class='col-md-6'>" + spec + "</div></div></div></div>";
}
counter++;
}
$(target).html("<div class='panel-body'><div class='container-fluid'>" + prefix + menu + sufix + "</div></div>");
}
I have 5 objects different, but one of these don´t show data, my webpage is in english and spanish, in english it charge all data, but in spanish one of these
doesn´t works and I get error at position 36, and position 36 is the item don´t show. Any idea what is wrong here? Regards
These one works
and this no works
---------Update------------
If I comment this line:
//obj = JSON.parse(items[item].Especificaciones);
and put
if(items[item].Especificaciones){
JSON.parse(items[item].Especificaciones);
}
it now runs with image, but now I don´t have my "Especificaciones" lists
Now when I use
var stringifyObj = JSON.stringify(items[item].Especificaciones);
var obj = JSON.parse(stringifyObj);
I get something like these:
make sure value is not null for the corresponding key inside JSON.parse. For example-
JSON.parse(items[item].Specifications)
make sure items have value in item index and items[item] has the property Specifications.
you can check if items[item].Specifications is not null before JSON.parse.
if(items[item].Specifications){
JSON.parse(items[item].Specifications)
}
Update
JSON.parse() is used to convert a string containing JSON notation into a Javascript object. To be valid JSON, strings must be in double quotes.
Try stringify the object and then parse again.
var stringifyObj = JSON.stringify(items[item].Especificaciones);
var obj = JSON.parse(stringifyObj);
The reason for the error is that JSON.parse() expects a String value and items[item].Especificaciones is an Array
"Eslora":100 pies"
You should probably opening the quotes when you start writing a string value

Populate the dropdown in order

I'm trying to populate my drop down in certain order (alphabetical order/alpha numeric order), but my code doesn't seems to be working. It is populating the value but not in order.
Here is my code
function dropdown(){
var html = html + "<option value='All'>All</option>";
var colValue = getColumn("COLUMN");
for( var i = 0; i < colValue.length; i++ ) {
var valueRow = colValue[i];
html = html + "<option value='" + valueRow.c + "'>" + valueRow.c + "-" + valueRow.v + "</option>";
}
$('#id').append(html);
}
here, COLUMN is the key that holds the value A1,A2,A3,B1
this code populate my drop down in the order A3,A1,A2,B1
I want my drop down to populate in the order A1,A2,A3,B1
while i did alert(html);i get the result
<option value='All'>All </option>";
<option value='A3'>A3-a3Value </option>";
<option value='A2'>A1-a2Value </option>";
<option value='A1'>A2-a1Value </option>";
<option value='B1'>B1-b1Value </option>";
and it is populating exactly in the same order.
My question is, what i need to do, to populate my dropdown in order?
I'm still in the beginner phase in java script and Jquery. Appreciate your help
Thanks
Based on what you are saying, it looks like colValue looks like this:
colValue = [
{ c="A3", v="a3Value" },
{ c="A1", v="a2Value" } // etc.
]
So you will need to decide what property to sort on, and then you can create a comparator:
function createComparator(property) {
return function(a, b) {
return a[property] > b[property];
};
}
You would use it like this:
colValue.sort(createComparator("c"));
Based on this SO answer: How to sort javascript objects based on their properties, specifying the property
You could try this:
function dropdown(){
var html = html + "<option value='All'>All</option>";
var colValue = getColumn("COLUMN");
colValue.sort();
for( var i = 0; i < colValue.length; i++ ) {
var valueRow = colValue[i];
html = html + "<option value='" + valueRow.c + "'>" + valueRow.c + "-" + valueRow.v + "</option>";
}
$('#id').append(html);
}
Since valueRow is an object instead of an array and you want to sort on valueRow.v you need more than Array.sort().
Take a look at lodash's sortBy: http://lodash.com/docs#sortBy
_.sortBy(valueRow, 'c')

Splitting an array before adding to combo list

I have a JSON object that returns several key value pairs. One of which is a Languages key and this contains comma separated values e.g "English, Hindi,French" etc
I'm trying to split the array before adding it to a combo list, but everything I try fails. Can anybody help, please?
$('#combolist-languages').html(function () {
var ret = '<option value="-1" selected>Select language_</option>',
u = user.slice(),
arr = [];
(function get() {
if (u.length) {
var v = u.shift();
if ($.inArray(v.Languages, arr) == -1) {
arr.push(v.Languages);
ret += '<option value="">' + v.Languages + '</option>';
}
get();
}
}());
return ret;
});
I'm just not sure where to put the split function. Thanks!
What about that?
var lang = 'English,Hindi,French';
var html = '<option value="-1" selected>Select language_</option>';
html += '<option value="">';
html += lang.split(',').join('</option><option value="">');
html += '</option>';
$('#combolist-languages').html(html);
Setting a value for each option with jQuery.map :
var lang = 'English,Hindi,French';
var html = '<option value="-1" selected>Select language_</option>';
$('#combolist-languages').html(
html + jQuery.map(lang.split(','), function (text, value) {
return '<option value="' + value + '">' + text + '</option>';
})
);

JSON object with arrays converted to HTML table

the below code is the JSON response i recieve from an API. unfortunately i cannot change the way this response is sent, i can only use this response as is within the scope of Javascript/jQuery.
My goal is to transform this into a HTML table.
I have attempted to do this already myself;
function CreateTableView(objArray, theme, enableHeader) {
// set optional theme parameter
if (theme === undefined) {
theme = 'mediumTable'; //default theme
}
if (enableHeader === undefined) {
enableHeader = true; //default enable headers
}
// If the returned data is an object do nothing, else try to parse
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '<table id="res" class="' + theme + '">';
// table head
if (enableHeader) {
str += '<thead><tr>';
for (var index in array[0]) {
str += '<th scope="col">' + index.toUpperCase() + '</th>';
}
str += '</tr></thead>';
}
// table body
str += '<tbody>';
for (var i = 0; i < array.length; i++) {
str += (i % 2 == 0) ? '<tr class="alt" id="' + array[i]['id'] + '">' : '<tr id="' + array[i]['id'] + '">';
for (var index in array[i]) {
str += '<td style="width:15%;">' + htmlspecialchars_decode(array[i][index]) + '</td>';
}
str += '<td>Edit</td><td>Delete</td></tr>';
}
str += '</tbody>'
str += '</table>';
return str;
}
However I am only able to get the headers to show... But it works well if the JSON response has only one array ie one row returned.
the code above was adapted from several other questions like this on Stackoverflow, I have spent days on this and cannot get these results to show in a table... This is just one example of many other that are returned just like this example and i will need to reuse this solution many times making it very important to me.
"ItemArray":{
"id":"14"
,"0":
{"id":"1","username":"guest","fname":"Guest","lname":"User","email":"example#domain.com","group":"member","active":"0","url":null,"last_activity":null}
,"1":
{"id":"2","username":"system","fname":"Internal","lname":"System","email":"example#domain.com","group":"member","active":"0","url":null,"last_activity":null}
,"2":
{"id":"3","username":"master","fname":"Super","lname":"Admin","email":"example#domain.com","group":"member","active":"0","url":null,"last_activity":null}
,"3":
{"id":"14","username":"apitest","fname":"API","lname":"Test","email":"user#domain.com","group":"member","active":"0","url":null,"last_activity":"2012-10-29 02:48:43"}
}
You can't use array.length for Object, so you need:
for (var o in array) if (array.hasOwnProperty(o)) {
var row = array[o];
}
Ok... The problem is the your item array is parsed into an object. Not an array.
If you log this:
typeof array.length
The result is undefined. So your loops doesn't get run.

Categories