Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON transformation for PHP

Tags:

json

php

Is there any reliable standardized way to transform JSON on the server side? (JSONT perhaps)

Can't really think of a way to use XSLT for that, or is there?

Edit: I should've been more specific. A somewhat standardized transformation is what I'm looking for: using json_decode and json_encode doesn't do that, it converts between formats. Converting one JSON string into another is what I'm curious about.

like image 716
Dennis Kreminsky Avatar asked Jan 11 '11 09:01

Dennis Kreminsky


2 Answers

PHP offers json_encode(), see the php manual on json_decode().
If you're receiving JSON values you can decode them with json_decode().
Those function require the JSON-extension installed (which is a default).

JSONT is a client side library to transform JSON data into HTML, to use it your client webpage has to implement http://goessner.net/download/prj/jsont/jsont.js. You just need to feed it with an json object containing the information.

For example if you want to add an link to this question:

<div id="jsont-space">
<?php
$jsontLink = new stdClass();
$jsontLink->uri = 'http://stackoverflow.com/questions/4656055/json-transformation-for-php';
$jsontLink->title = 'Question on Stackoverflow about: JSON transformation for PHP';
?>
<script type="text/javascript">
var transforms = { "self": "<a href=\"{uri}\" title='{title}'>{$.title}</a>" };
var data = <?php echo json_encode($jsontLink); ?>;
document.write(jsonT(data, transforms));
</script>
</div>

This is of course something very quick&dirty. But it should explain the whole variant of

  • defining the data
  • defining transformations
  • applying those to a page

here are some additional examples on JSONT (look @ source)

Edit:
Added information about JSONT & implementation example

like image 108
Samuel Herzog Avatar answered Sep 16 '22 17:09

Samuel Herzog


$my_array=array("first", "second", "third"); 

json_encode($my_array); //["first","second","third"]

As of php version 5.3 you can:

json_encode($my_array, JSON_FORCE_OBJECT); // {"0":"first", "1":"second","2":"third"}
like image 27
Diablo Avatar answered Sep 19 '22 17:09

Diablo