How to read a Json file

Asked

Viewed 3,151 times

5

$(document).ready(function(){
var json = [{
    bloco:"bloco1",
    titulo: "titulo1",
    perguntas: [{
        pergunta1: "Resposta1",
        opcaoSelecionada: "2"
            }];
}/*,{
    bloco:"bloco2",
    titulo: "titulo2",
    perguntas: [{
        pergunta2: "Resposta2",
        opcaoSelecionada: "2"
            }];*/
];    
//var obj = jQuery.parseJSON(json);

    alert(JSON.stringify(json));
    //alert(obj.bloco);
});

I am learning Json, and would like to know if this structure is built correctly. The idea is to store all the information inside a array of objects, which will be generated from data filled on the front.

Then I will send this information via Ajax to PHP to build a structure to display the data. Could also tell me how I would read this file in PHP/javascript with a loop?

3 answers

3

PHP has a function called json_decode

$matriz = array();
$matriz = json_decode($json);

which passes json to an array. never tested but should work , in case if the json is well built but if you experiment with the function I told you and all right, with the code below you can check how this structure and see if you like.

echo "<pre>"; 
print_r($matriz);
echo "</pre>";

1

To read a JSON file with Javascript you can use the function jQuery.getJSON:

$.getJSON( "caminho_do_arquivo/arquivo.json", function( data ) {
    // processe os dados aqui
});

The complete documentation of the method jQuery.getJSON is on the page http://api.jquery.com/jquery.getjson/

0


The JSON notation is quite similar to that of an object in Javascript, except for a few differences:

Javascript object:

[
    {
       "bloco":"bloco1",    // Uso de aspas duplas 
       'titulo': "titulo1", // aspas simples é
       perguntas: [{        // opcional
          pergunta1: "Resposta1",
          opcaoSelecionada: 2 // Valores numéricos são permitido
       }], // Não se usa ; no final de um elemento nem para separar-los
       callback: function(){ alert('Hello World!'); }
    }
]

An object notation in Javascript is very flexible and simple. You can still add other elements after creating the object:

objeto[ 'chave' ] = 'Valor';
objeto[ 'outra' ] = {name: 'Objeto Filho', value: 'Outro valor' };

JSON:

[
    {
       "bloco":"bloco1",    // Uso de aspas duplas é obrigatório
       "titulo": "titulo1", // aspas simples não é permitido
       "perguntas": [{
          "pergunta1": "Resposta1",
          "opcaoSelecionada": 2 // Valores numéricos são permitido
       }] // Não se usa ; no final de um elemento nem para separar-los
       // Não é permitido funções
    }
]

You can send your data as an object by $.ajax, and receive them as form fields in PHP

var dados = [
  {
    bloco: "bloco1", titulo: "titulo1", perguntas: [
      {pergunta: "Pergunta1", opcao: 2},
      {pergunta: "Pergunta2", opcao: 1},
      {pergunta: "Pergunta3", opcao: 4}
    ]
  }
]

$.ajax({
  url: '/path/to/file',
  type: 'POST',
  dataType: 'json',
  data: {blocos: dados},
  success: function(data){
    alert(data.msg);
  }, 
  error: console.log
});

In PHP you can receive the data as POST variables, as reported in the property type of ajax:

$blocos = (!empty($_POST['blocos']) ? $_POST['blocos'] : NULL);

$msg = '';

foreach ($blocos as $bloco) {
    $msg .= "Bloco: $bloco['bloco'] <br>\n".
            "Título: $bloco['titulo'] <br>\n";

    foreach ($bloco['perguntas'] as $pergunta) {
        $msg .= "Pergunta: $pergunta['pergunta'] <br>\n".
                "Resposta: $pergunta['opcao'] <br>\n";
    }

    $msg .= "<br>\n<br>\n";

}

header('Content-Type: application/json');
echo json_encode(
    Array( 
        'msg' => $msg 
    )
);
exit;

You can also send the data as a string and decode it as the function json_decode:

$.ajax({
  url: '/path/to/file',
  type: 'POST',
  dataType: 'json',
  data: {blocos: JSON.stringify(dados)},
  success: function(data){
    alert(data.msg);
  }, 
  error: console.log
});

When the object is sent directly in the parameter data of $.ajax, jQuery takes care of these data correctly. But when you turn the object into one string in JSON format using JSON.stringify(dados) it is necessary to decode this string in PHP:

<?php

    $blocos = (!empty($_POST['blocos']) ? json_decode($_POST['blocos']) : NULL);

Browser other questions tagged

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