Difference between JSON and String data

Asked

Viewed 1,956 times

9

I’m just finishing building a website on PHP with architecture MVC, the next step is to integrate the application (I only have the interface) with the core(controller) site, to fetch information from the database. This will be done with Ajax because the application is hybrid, in HTML, with the Intel XDK.

I want to know the best way to carry this data:

  • Sending Ajax to the site and returning a JSON, thus manipulating the array to use in the app.

  • Sending Ajax to the site and on it mounting a string coded HTML and returning it to the app to use this HTML on its interface.

I see the second best option because of my greater familiarity with PHP, but which of the two options requires less device internet speed and compromises less app performance? I know it’s a theoretical question and it risks being negative, but in my view it’s a valid question, not based on opinions since it derives from performance and not from what you think is best.

  • For the little I know the advantage of [JSON] is its human reading and its ease of writing without as many tags as in [XML] for example. In terms of benchmarking remember that the [JSON] you will have to build all the elements, use something like the [Mustache] and probably the user request will be more dynamic, It may take a little longer while in HTML the delay would only be to treat the elements one by one, the consumption will be higher. I didn’t have much time to research and study about it so I don’t know much about it, but I hope I helped a little bit.

  • JSON facilitates the front and back side, because it carries a list of objects, which can be interpreted by the assigned tags, making it easy to read for javascript and to control.

  • Gives an example of the HTML you have in mind to use.

5 answers

12

Dude,

I will abstain from comparisons between JSON and XML and keep the focus on what you asked.

You put it like this:

I want to know the best way to carry this data:

  • Sending Ajax to the site and returning a JSON, thus manipulating the array to use in the application.
  • Sending Ajax to and on the site assembling a string with HTML code and returning it to the application use this HTML in your interface.

And for me in your own question you’ve already offered the answer.

I want to know the best way to transport these dice.

In my little experience, I believe that when you make an ajax request what you are looking for from the server are dice and nothing more than that.

I don’t think the return of HTML code is good practice for some reasons:

  • Usually pollutes the backend code with endless HTML tags being concatenated
  • You prevent that ajax url from being used elsewhere in your project, as not everyone who needs those dice, you need that HTML.

Anyway, I would choose to return only the data to your frontend and treat all the HTML you need there anyway.

Plus I found this little one discussion at Stackoverflow. I think you’d better take a look and draw your own conclusions.

9

Do not invent the wheel, use JSON!

There are several formats to be used for data transport, but in my understanding JSON is the best format currently because it is being widely used, IE, programming languages are adapted to conversions:

  • Object for JSON
  • JSON for Object

It is also a more compact format than XML.

With a String you would first have to create a pattern that only you would understand or who had your source code to analyze, different from JSON that (as had previously) is already "massified".

Example

In a "Owner" class you would have to create a function to turn the data into JSON and also have to have a method to transform JSON into an instance of an Owner. With JSON these methods probably already exist natively or through a third-party code.

JSON VS XML

class Proprietario { id, nome }

Json

"proprietario":{"id":1,"nome":"Victor"}

XML

<proprietario>
    <id>1</id>
    <nome>victor</nome>
</proprietario>

Note that the size of JSON even on such a small scale is much smaller, imagine in a list with 1000 owners.

Completion

No use reinventing the wheel not using something that works and is already widely tested.

4


Sending Ajax to the site and returning a JSON, thus manipulating the array to use in the application.

In that case, the required Javascript code will be much larger, since it contains the logic to display the data.

That means you’re gonna have to load more Javascript before displaying the data.

But this can be paid over time if the data is loaded several times without reloading the page, since the amount of data transmitted is less per request.

This approach tends to present best performance, but also greater complexity and soon your code base can become chaos unless you and the rest of the team are disciplined developers and write modular Javascript (AMD, ES 6).

Sending Ajax to and on the site by assembling a string with HTML code and returning it to the application to use this HTML in its interface.

The Javascript tends to be much simpler and concise, however the amount of data transmitted per request is much higher.

Switching in kids, the site loads faster, but with each new asynchronous update it will consume a little more bandwidth and server processing.

Another problem with this approach is that it can be complex to keep sections of the page separate from the main page that are sometimes rendered within the context of the page, either independently. Without a good organization and a good rendering engine this tends to generate spaghetti or duplicate code.

Usually pollutes the backend code with endless HTML tags being concatenated

Not necessarily. In PHP you can have snippets of templates that can be rendered independently or in conjunction with the page. Some frameworks allow you to create components or widgets that work that way.

You prevent that ajax url from being used elsewhere in your project, because not everyone who needs that data needs that HTML.

Rendering HTML definitely docks the service with your page, but nothing prevents you from maintaining public services in JSON and private in HTML separately.

In my experience, third-party data consumers usually have a different view of the data. Not always the case, but trying to maintain a single API for internal and external use can be a much bigger headache, as you get stuck by the API contract that can’t break for external systems.

Anyway, I would choose to return only the data to your frontend and treat all the HTML you need there anyway.

From an architectural point of view this is more sophisticated form, the current trend and preference of the vast majority of front end developers, for enabling:

  • Better separation of concepts: does not divide the rendering logic between client and server, but focuses on client
  • Flexibility: allows the evolution of the independent front end of Apis or back end services.

Finally, if you’re really concerned about performance, consider using a more compact protocol than JSON, such as Protobuf from Google. See some advantages here and a PHP implementation here.

  • 1

    Very well explained man.

  • 1

    It is worth saying that Protocol Buffer is a return to the past, and that pleases me. Binary formats such as IFF and its derivatives were very common a few years ago. They were simple to use and very compact. Then people started to want to make formats to read machine that were readable to humans, getting to the XML scam (which even though it even has its niche, turned out to be fashionable). Then finally they began to realize that it is an "expensive" and unnecessary luxury, and they are going back to packing what is machine, for the machine to read. As for the answer, it added value to the discussion. + 1

  • @Bacco had not been thinking from this angle yet - about the return to the past, but it is the purest truth. A human readable format is pleasant for the developer, but few stop to calculate the price of it.

4

The best way to carry this data is through JSON, it is used in various service distributors through REST (Representational State Transfer). In the past XML was used for this.

There are some reasons why you do not send the data in HTML, among them:

  1. The file sent will be with a lot of useless information;
  2. You will need to weed information within it, and a change in page layout may compromise your application;
  3. You won’t find much on the internet about this method of yours;
  4. It will only work for you because it will not follow a pattern depending on the HTML content

Some reasons to use JSON: 1. JSON is the standard adopted by large companies for sending and receiving data between applications. Facebook, twitter and Google itself use it; 2. It is lighter than XML because it does not have huge tags and this will save you bandwidth, if your application is over the internet and time; 3. You may follow the REST standard through the HTTP protocol and provide services to third parties in the future, if applicable. 4. There are JSON to Object and Object to JSON converters in several languages 5. If you need to maintain your website, your JSON services will not be compromised and your application will continue running normally, i.e., regardless of the HTML site.

HTML VS JSON VS XML

I see the second best option because of my greater familiarity with PHP, but which of the two options requires less internet speed of the device and less compromises the performance of the app?

The download time of the information will be longer and the performance of the app will be reduced if you opt for HTML, since JSON features a simple architecture. Just to illustrate better follow an example related to the user:

In JSON:

{"nome":"Anderson"}

In HTML:

<html>
<title>Dados do usuário</title>
<body>
<div id="container">
<h1>Dados do usuário</h1>
<div class="algumacoisa">
<p>Nome do usuário:<span id="nomedousuario">Anderson</span></p>
</div>
</div>
</body>
</html>

In XML:

<nomedousuario>Anderson</nomedousuario>

The size of the files as you can see is very different, while JSON is simple and only has relevant information, HTML has a lot of useless information (for the app) and the handling difficulty to get the desired information will be much greater and XML presents tags that make the file much larger than JSON. You can use JSON and XML, prioritizing JSON, but do not use pure HTML as if it were a service because it is too heavy to perform this function.

Completion

Recommend:

  1. Use Object Orientation
  2. Use the REST architecture with JSON and/or XML, the two can live in the same application and without much difficulty;
  3. Read a little more about HTTP protocols to better understand what happens behind the scenes;

In short: follow existing standards.

I hope I helped and I put myself at your disposal.

Hug!


Here are some links that can help you:

Introduction to REST

How to create a basic web service with PHP - English page

Working with JSON in PHP

  • 1

    Just one detail, when returning with html you never use an entire page, from the html tag etc, but part of the code, such as a paragraph, a button or a thumbnail.

  • @lvcs vc talk about using html, as a text file and not as html? If so, you wouldn’t have the basics to be true html. I explained based on the minimum to consider an HTML, but later one can take a part of the page (button, div, paragraph etc), but without ceasing to have basic html tags.

  • No, when use is almost equal l your example, but in case only return the p tag, and not all the code of a page, return the p tag and with jquery add this return as html of a specific div.

  • But jquery, for example, does a back-up reading of the whole page in order to extract part of it. I’ve done this in old projects through ajax.

2

" ... I want to know the best way to carry this data: ..."

It was not very clear to me if your question is to send something to the server or if it is to get back from the server ("Sending Ajax to the site").

I imagine that’s when you receive information from the server via JSON. But I will post here a piece of my code that I always use for situations involving JSON both to send to PHP, and to receive from the server to be treated in JS.

As many have already discussed above, don’t rehash the wheel, use JSON. But this approach uses a mixed solution, after all transforms JSON into a string, to improve performance during the transfer process.

//Aqui é o seu código PHP (seuSErvidor.php).
//Recuperando as informações enviadas do Javascript para o php, FrontENd=>BackEnd.

$ObjEvn=$_POST["ObjEvn"];//valor = btn_Login
$dataJsToPHP=$_POST["dataJsToPHP"];//valor do input "#txt_EmailLogin"
$eviarQQCoisa=$_POST["eviarQQCoisa"];//Valor 123

//NOTA: Não é aconselhado recuperar valores enviados de JS sem um tratamento prévio. Geralmente eu faço as validações no lado javascript.

//aqui vc pode direcionar o seu fluxo(processo). Pode ser uma página admin, por exemplo que vai gerenciar todos direcionamentos como um controler.
if($ObjEvn=="btn_Login"){
    //Código para testar login de usuário .... depois crie sua array $arrToJSON para ser enviada para javascript.
}
elseif($ObjEvn=="btn_DeleteUsuario"){
    //Código para deletar usuário .... depois crie sua array $arrToJSON para ser enviada para javascript.
}
elseif($ObjEvn=="btn_QualquerAcao"){
    //Código para outras ações  .... depois crie sua array $arrToJSON para ser enviada para javascript.
}



//Depois de fazer suas consultas no banco de dados, vc pode enviar os dados     para uma array php. Note que vc pode criar quantos índices vc quiser e colocar o que quiser dentro da array, incluisive código HTML, com javascript embutido. Funciona perfeitamente para mim. Eu carrego páginas inteiras utilizando essa técnica.
        //Crie sua array  
        $arrToJSON = array(
          "dataPHPtoJs"=>"algumDado de quaqluer formato",
          "htmlToPHP"=>"<div class=\".class1\">algum código html aqui</div>"    
        );  
        //Nota: a depender do tamanho da informação que vc quer guardar em "htmlToPHP" talvez precise usar um código para escapar espaços e carateres especiais. Vou colocar a função logo abaixo.

        //Essa função pega a array e transforma numa representação JSON - string. http://php.net/manual/en/function.json-encode.php

        return json_encode(array($arrToJSON));




    //No seu lado javascript ou "SITE" como vc disse. O evento foi iniciado pelo elemento "#idElement". Pode ser um click ou qualquer outra coisa. Vc vai mandar algo para o PHP (o codigo acima) e vai receber a $arrToJSON (que agora é uma string) no processo return

    $(document).on("event", "#idElement", function(){
        //Veja que aqui vc tbm está enviando para o PHP o objeto
         var dt={ 
                  ObjEvn:"btn_Login",
                  dataJsToPHP: $("#txt_EmailLogin").val(),
                  eviarQQCoisa: 123
                };

        //Ajax      
         var request =$.ajax({//http://api.jquery.com/jQuery.ajax/
                                url: "seuSErvidor.php",
                                type: "POST",
                                data: dt,
                                dataType: "json"
                            });

        //Então quando requisição AJAX estiver terminada, vc acabou de receber do seu PHP uma string que vai ser tratada aqui em javascript

            request.done(function(dataset){
                for (var index in dataset){ 
                     dataPHPtoJsJS=dataset[index].dataPHPtoJs;//Aqui é o index da array que vc usou no php.
                     htmlToJS=dataset[index].htmlToPHP;
                 }

                 //Aqui vc pode usar o que recebeu do PHP e modificar as sua página de acordo com o recebido. POde carregar htmls interios, inclusive.

                 if(dataPHPtoJsJS){
                    $( "#idseuElemento1" ).removeClass( "class1" );
                    $( "#idseuElemento2" ).html( htmlToJS );
                 }


         }); 

        //Ajax Fail 
            request.fail(function(jqXHR, textStatus) {
                alert("Request failed: " + textStatus);
            }); 
    }

//Função para filtrar espaços (ou minimizar) javascript ou HTML


function html_rows_Event_Details() {

$str =<<<eof
  <tr class='evntdet'>
      <td colspan='4' style='background-color:#00BABF ;  padding: 10px;  text-align: center;'>
          Something
      </td>
  </tr>
eof;



$re = "/(?:\\s*([<>])\\s*|(\\s)\\s*)/im"; 
$subst = "$1$2"; 

return  preg_replace($re, $subst, $str);

}

Source: Link.

  • With the two cases I mentioned in the question this clear that are the return data, since the ones that send are always by Ajax independent of the form, the variable in the two cases are the return.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.