Simple JSON Example code needed

Hi all,

Has anyone got any links / sample code on a simple example on how to List/Edit/Add and Delete from a JSON file?

Javascript and/or PHP would be fine.

Thanks
error77Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

BadotzCommented:
Read the file into a var, then use normal JavaScript to modify it?
0
Ray PaseurCommented:
PHP has JSON functions that may be helpful.  See the examples on the man pages.
http://php.net/manual/en/book.json.php
http://php.net/manual/en/function.json-encode.php
http://php.net/manual/en/function.json-decode.php

JSON encoding does not produce a file - it produces a string.  Since almost any data type can be JSON encoded, I would just do the data manipulation on the array or object before using json_encode(), rather than trying to manipulate the JSON string.

HTH, ~Ray
0
Ray PaseurCommented:
To see this in action, go to http://www.laprbass.com/RAY_temp_ivangarcete.php

Not very exciting, but it shows what is going on at the "hello world" level.  Since JSON assumes UTF-8 you have issues with the use of the special western characters above character code #128.  This little script answers the question, "How do I deal with ISO-8859-1 character sets in JSON?"
<?php // RAY_temp_ivangarcete.php
error_reporting(E_ALL);
echo "<pre>";

// TEXT WITH A SPANISH CHARACTER
$text = "España";
echo PHP_EOL . $text;

// URL-ENCODED FOR TRANSPORT
$code = urlEncode($text);
echo PHP_EOL . $code;

// JSON-ENCODED
$json = json_encode($code);
var_dump($json);

// DECODED
$back = json_decode($json);
var_dump($back);

// URL-DECODED
$mine = urlDecode($back);
echo PHP_EOL . $mine;

// SELF TEST
if ($text == $mine) echo PHP_EOL . 'SUCCESS!';

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

XzKtoCommented:
I dont understand what exactly you want to do, so I wrote a simple class to work with JSON files, i hope it can be a good place to start doing what you want.

<?php

class MyJson {

    private $data = NULL;
    private $json_file=NULL;

    /**
     * You can format warning output here.
     * @param string $warning_string Warning string
     */
    private function warning($warning_string) {
        echo 'Warning: ' . $warning_string . "\n";
        return NULL;
    }

    /**
     * You can format error output here.
     * @param string $error_string Error string
     */
    private function error($error_string) {
        die('Error: ' . $error_string . "\n");
    }

    /**
     * Constructor - will read and decode json data from file
     * @param Mixed $json_file Json file name string or FALSE to use empty data
     * @param bool $if_assoc True if json objects should be converted to arrays.
     * @param int $depth Maximum depth of json
     */
    public function __construct($json_file=FALSE, $if_assoc=false, $depth=512) {
        if ($json_file) {
            $json_file=(string)$json_file;
            $this->json_file=$json_file;
            //Check if we can read file
            if (!is_readable($json_file)) {
                $this->error('Cant read json file, file does not exist or permission denied!');
            }
            //Get file contents
            $json_string = file_get_contents($json_file);
            if ($json_string === FALSE) {
                $this->error('Cant read json file!');
            }
        }
        else {
            $json_string='{}';
        }
        //Convert json string to PHP objetcs/arrays
        $this->data = json_decode($json_string, $if_assoc, $depth);
        if ($this->data === NULL) {
            $this->error('Json decoding failed with error code "' . json_last_error() . '"!');
        }
    }

    //Get path array by path string
    private function get_path_arr($path) {
        $_path = trim((string) $path, '/');
        return explode('/', $_path);
    }

    /**
     * Function to get JSON element by path
     * @param string $path - path of JSON element
     * @param string $expected_type Expected return type - 'string','int' or 'array'
     * @return bool Returns element on success, NULL on failure
     */
    public function get($path, $expected_type=NULL) {
        //Trim "/" from the begining or end of "$path" string
        $path_arr = $this->get_path_arr($path);
        $search_data = $this->data;
        foreach ($path_arr AS $path_elem) {
            switch (gettype($search_data)) {
                case 'object':
                    if (!isset($search_data->{$path_elem})) {
                        return $this->warning('Cant find element with path "' . $path . '"!');
                    }
                    $search_data = $search_data->{$path_elem};
                    break;
                case 'array':
                    if (!isset($search_data[$path_elem])) {
                        return $this->warning('Cant find element with path "' . $path . '"!');
                    }
                    $search_data = $search_data[$path_elem];
                    break;
                default:
                    return $this->warning('Cant find element with path "' . $path . '"!');
            }
        }
        switch ($expected_type) {
            case 'int':
                return (int) $search_data;
            case 'string':
                return (string) $search_data;
            case 'array':
                return (array) $search_data;
            default:
                return $search_data;
        }
    }

    public function set($element, $path='', $if_create=true) {
        $path_arr = $this->get_path_arr($path);
        $search_data = &$this->data;
        foreach ($path_arr AS $path_elem) {
            switch (gettype($search_data)) {
                case 'object':
                    if (!isset($search_data->{$path_elem})) {
                        if ($if_create) {
                            $search_data->{$path_elem} = array();
                        } else {
                            return $this->warning('Cant find element with path "' . $path . '"!');
                        }
                    }
                    $search_data = &$search_data->{$path_elem};
                    break;
                case 'array':
                    if (!isset($search_data[$path_elem])) {
                        if ($if_create) {
                            $search_data[$path_elem] = array();
                        } else {
                            return $this->warning('Cant find element with path "' . $path . '"!');
                        }
                    }
                    $search_data = &$search_data[$path_elem];
                    break;
                default:
                    return $this->warning('Cant find element with path "' . $path . '"!');
            }
        }

        $search_data=$element;
        return TRUE;
    }

    /**
     * Saves json file
     * @param string $filename File name of file to save json data
     * @param int $encode_options Json encoding options, passed to json_encode()
     */
    public function save($filename=FALSE,$encode_options=0) {
        if(!$filename) {
            $filename=$this->json_file;
        }
        if(!$filename) {
            $this->error('Can\'t save JSON file! No filename specified!');
        }
        $json_string=json_encode($this->data,$encode_options);
        if(!$json_string) {
            $this->error('Can\'t save JSON file! Json encoding failed for some reason, last error code: "'.json_last_error().'"!');
        }
        if(!file_put_contents($filename,$json_string)) {
            $this->error('Cant save JSON file for some reason!');
        }
    }
}
class TestClass {
    public $class_arr=array(
        'class_arr_key' => 'class_arr_value'
    );
}
$test_class_inst=new TestClass();


$json_obj=new MyJson(FALSE);
$json_obj->set(array('arr_key'=>'arr_value'),'/home/test_array/');
$json_obj->set($test_class_inst,'/home/test_class/');
$json_obj->save('test_json.json');

$another_json_obj=new MyJson('test_json.json');
echo $another_json_obj->get('/home/test_array/arr_key')."\n";
echo $another_json_obj->get('/home/test_class/class_arr/class_arr_key')."\n";
print_r($another_json_obj->get('/home/test_class/class_arr/'));

Open in new window

0
error77Author Commented:
I'm I right in assuming the JSON is not really mean't for normal DB stuff ? I have some code the writes to json ... then I want to create a simple cms to read the json / edit / delete / add ... etc...

Is this not the right way please?

thanks
0
XzKtoCommented:
I want to create a simple cms to read the json / edit / delete / add
You can do that with the class I posted.

Working with files is usually much slower then working with DB, DB does lots of usefull stuff (like indexes, proper disk read/writes, locking tables, transactions etc.) for you, so I doubt anyone can write any function/class that will work with files and will run as fast as DB, and it is impossible, imho, with JSON. When changing value in JSON file you usually can't just change a few bytes, you will need to change whole file.

But, if you want to do something just for fun, then you can use my class to get/set values, but of course in case of multiple simultaneous connection it will most likely crash as it uses the same file.

If you want to use files, you should look at how PHP sessions work, as it works with files by default.

TLDR: No, using JSON file as DB is almost never a good idea.
0
XzKtoCommented:
Forgot: you can work around problems with multiple access to same file with flock, but it still is not a very good idea.
0
Ray PaseurCommented:
assuming the JSON is not really mean't for normal DB stuff

You can say that again, in the same way that a butcher knife is not really meant for playing catch.  A baseball is a better choice, and there are better choices for DB stuff than JSON.  JSON data is a string, not a DB.

JSON is an encoding mechanism used for data transport and storage.  In that way, it is like XML or the PHP function serialize().  Please read the man page here, taking note of the important quote, Generates a storable representation of a value ... This is useful for storing or passing PHP values around without losing their type and structure.
http://us3.php.net/manual/en/function.serialize.php

If you want to change serialized data, you would unserialize it and make it into the array or object (or whatever) that is subject to the logic rules of your PHP script.  Make your changes there, then serialize it again for transport or storage.  If you want to change information in an XML string, you would make it into an object and modify the nodes using OOP notation, then render it as XML for storage or transport.  JSON works the same way, as the JSON function man pages posted above clearly show.

Don't write a CMS to read/edit/delete/add JSON.  JSON is the wrong tool.  Use a data base instead.  Millions of Wordpress clients have proved that approach works.

Best regards, ~Ray
0
XzKtoCommented:
Ray_Paseur:

I think that your post brings wrong message. We dont always have to read whole file to work with data in it, even with formats like JSON/XML: you can access raw data written in file by some rules (or even make some kind of indexes in separate file), no need for OOP classes or anything. More important is that you need to change big part of file if you insert a node in the middle of JSON structure and that is too costly.

You are saying that JSON is only encoding mechanism and that is not true, imho. If you specify that there should be no meaningless spaces in JSON output(standard PHP behaviour) then JSON defines data structure in file. The main thing here is difference between MySql data structure and JSON data structure: JSON data structure is not adapted for "cheap"(few read/writes) changes in file when some data is changed.
0
XzKtoCommented:
To clarify myself: if we need to change last value in JSON file, we can read file from the end to begining, find first value that we meet(using JSON standards) change it then simply write all data that we read before after it. In this operation there is no need to create objects,arrays or anything and we perform read/write on only small part of file. PHP supports all the things we need: fseek etc.
0
error77Author Commented:
Thanks a lot for your help. Let me read it all and digest later.

Just a note:

I have 2 of some code.

1. Already saves and reads to JSON

2. Part 2 is what this question is about where I have this (Separate) part of the program where the admin Adds/Edit/Delete's etc the code but it needs to read the Json.

So, Do I read this JSON file created by part 1 directly or put it in the DB and then have my part 2 of the program do it's stuff there.

I hope you understand my issue.

THanks again
0
Ray PaseurCommented:
@XzKto: I think we can agree to disagree on this.  When I am new to a PHP function I like to read the PHP man page and take in the user-contributed notes.  There are many such notes on this page, and not one of them suggests using a JSON string for data base functions.  My sense is that if this were a good design pattern someone would have mentioned it already.  JSON_Encode() is not exactly a new PHP function.
http://www.php.net/manual/en/function.json-encode.php

Our asker mentioned a CMS.  A CMS, as I understand the context, is a "Content Management System" and that makes me think that there needs to be a set of relationships established in the data - who owns the pages, who approves the pages, what pages get produced on the web site, things like that.  JSON does not have that capability - it's a string of characters.  It is a little more sophisticated than a CSV string and a little less sophisticated than serialized objects or XML strings.  JSON is not a relational data base.
0
Ray PaseurCommented:
@error77: Please post an example of the code and the test data you are using.  I am sure we can help you find a useful design pattern.  Thanks, ~Ray
0
XzKtoCommented:
@Ray_Paseur:

I think we can agree to disagree on this.  When I am new to a PHP function I like to read the PHP man page and take in the user-contributed notes.  There are many such notes on this page, and not one of them suggests using a JSON string for data base functions.  My sense is that if this were a good design pattern someone would have mentioned it already.  JSON_Encode() is not exactly a new PHP function.
I read man pages too, but "If it wasn't already made it doesn't work" approach is kinda lame.


Our asker mentioned a CMS.  A CMS, as I understand the context, is a "Content Management System" and that makes me think that there needs to be a set of relationships established in the data - who owns the pages, who approves the pages, what pages get produced on the web site, things like that.  JSON does not have that capability - it's a string of characters.  It is a little more sophisticated than a CSV string and a little less sophisticated than serialized objects or XML strings.  JSON is not a relational data base.

This is completely wrong. You can represent all MySql data in JSON format. I will say more, MySql tables can be dumped completely(of course without indexes,functions and other MySql-related stuff) into even CSV files, JSON is even easier, something like this:

array(
    'database1' => array(
        'table_1' => array(
                'row_1' => array(
                    'filed1' => 'field1_value',
                    'filed2' => 'field1_value',
                ),
                'row_2' => array(
                    'filed1' => 'field1_value',
                    'filed2' => 'field1_value',
                )
        ),
        'table_2' => array(
            
        )
    )
)

Open in new window

Just turn this PHP array into JSON using json_encode() and here you are: mysql database in JSON format.
0
Ray PaseurCommented:
You're joking, right?  Is there any real-world application that demonstrates what you're describing here?  I've certainly never seen one.

Anyway, I will sign off on this question now.  A complete and accurate answer was given at ID:35371064.  Best regards to all, ~Ray
0
XzKtoCommented:
@Ray_Paseur:

You're joking, right?  Is there any real-world application that demonstrates what you're describing here?  I've certainly never seen one.

Again "if i never saw it, it doesn't exist" doesn't really work in real world. You need to explain why it doesn't work, and you didn't.
0
BadotzCommented:
XzKto:
If you have to access the DB in order to create JSON from it, what is the point of that? You add an unnecessary step for what? To demonstrate that something is possible?

error77:
Could you encode your entire DB as XML and perform CRUD on a single file? Sure, but not in a production environment. In the same way you could encode your entire DB as JSON.

But here you see what XML and JSON really are: data exchange formats. You can encode data from an Oracle DB into JSON and then insert it into a MySql DB because JSON neutralizes the differences between the two DBs.

To over-simplify, I use JSON on the client and a DB on the server. I pass data (as JSON) via Ajax. You might consider doing the same.
0
XzKtoCommented:
@Badotz:

If you have to access the DB in order to create JSON from it, what is the point of that? You add an unnecessary step for what? To demonstrate that something is possible?
Please, dont put words into my mouth. If you refer to my comment to "You can represent all MySql data in JSON format" I was just saying that you can, it was answer to Ray_Paseur's comment, I even quoted it.
0
XzKtoCommented:
Sorry, I reread your post again and yes, it was only to "demonstrate that something is possible", because Ray_Paseur was claiming that it is impossible.
0
XzKtoCommented:
Sorry again, my co-worker pointed out that my last post was unclear. You don't need access to MySql to create JSON that will represent it. You can just create the same data structure in JSON originally. I used MySql only as example of popular database.
0
BadotzCommented:
Then I think we can all agree that that JSON (or XML or tab-delimited data) alone is not a replacement for a database in a production environment.

This is not to say it cannot be done, but that it makes no sense to do it.
0
XzKtoCommented:
@Badotz:
I agree completely, and I am sorry for derailing this thread. I just don't think it is right when someone explains correct answer with wrong reasons.
0
error77Author Commented:
Thanks all. All that information was priceless.
0
BadotzCommented:
(sigh) but pointless ;-)
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.