Skip to content

Instantly share code, notes, and snippets.

@lucas1 lucas1/wjson.pod
Last active Aug 29, 2015

Embed
What would you like to do?
Escrevendo JSON de forma simples em Perl

Escrevendo JSON de forma simples em Perl com o módulo WJSON

Introdução

Como uso muito JSON no meu dia a dia e apesar de existir excelentes módulos Perl para escrever JSON. Eu resolvi criar o módulo WJSON que facilita muito para escrever JSON com Perl.

Instalação

Primeiro instale o módulo App::cpanminus

$ cpan App::cpanminus

Depois de instale o módulo WJSON

$ cpanm WJSON

O módulo tem dependências dos módulos Moose, JSON, Encode e Tie::IxHash.

Atributos

encoding

Com esse atributo você seta o encoding do json, se não setar nenhum valor o padrão é utf-8

my $wjson = new WJSON(encoding => 'iso-8859-1');
ou
my $wjson = new WJSON;
$wjson->encoding('iso-8859-1');

variable

Com esse atributo você seta um nome para uma variável quer retornará com JSON

my $wjson = new WJSON(variable => 'json');
ou
my $wjson = new WJSON;
$wjson->variable('json');

ordering

Com esse atributo você pode ordenar o JSON, lembrando que hash em Perl não é ordenado, se ordenar seu JSON dependendo do tamanho pode perder um pouco de desempenho

my $wjson = new WJSON(ordering => 1);
ou
my $wjson = new WJSON;
$wjson->ordering(1);

Métodos

Open

Abre um object ou array, você precisa setar um nome

$wjson->Open('Foo');

Close

Fecha um object ou array, trabalha em conjunto com o método Open. Setar 1 separa da referencia atual, setar 2 adicionar o valor dentro de um array, setar 3 é os dois juntos

$wjson->Close();
ou
$wjson->Close(1);

Object

Cria objects, precisa setar índices e valores

$wjson->Object(
   indice1 => valor1,
   indice2 => valor2,
   indice2 => valor3
);
ou
$wjson->Object(
   {
      indice1 => 'valor1',
      indice2 => 'valor2',
      indice3 => 'valor3',
   },
   {
      indice4 => 'valor4',
      indice5 => 'valor5',
      indice6 => 'valor6',
   }
);

Array

Cria arrays, precisa setar os valores

$wjson->Array('valor1', 'valor2', 'valor3');
ou
$wjson->Array('valor1');
$wjson->Array('valor2');
$wjson->Array('valor3');
ou
$wjson->Array(['valor1', 'valor2', 'valor3'], ['valor4', 'valor5', 'valor6']);

Header

Retorna o cabeçalho para JSON

return "application/json";

HeaderJS

Retorna o cabeçalho para JavaScript

return "application/javascript";

HeaderCGI

Retorna o cabeçalho para JSON em CGI

return "Content-type: application/json\n\n";

HeaderJSCGI

Retorna o cabeçalho para JavaScript em CGI

return "Content-type: application/javascript\n\n";

Print

Retorna o JSON

Exemplos

Exemplo 1

#!/usr/bin/perl

use strict;
use warnings;
use WJSON;

my $wjson = new WJSON(encoding => 'iso-8859-1');
$wjson->Array('valor1', 'valor_2', 'valor3');
print $wjson->HeaderCGI;
print $wjson->Print;

retornara:

["valor1","valor2","valor3"]

Exemplo 2

#!/usr/bin/perl

use strict;
use warnings;
use WJSON;

my $wjson = new WJSON();
$wjson->Object(
    indice1 => 'valor1',
    indice2 => 'valor2',
    indice3 => 'valor3',
);
print $wjson->HeaderCGI;
print $wjson->Print;

retornara:

{"indice1":"valor1","indice3":"valor3","indice2":"valor2"}

Exemplo 3

#!/usr/bin/perl

use strict;
use warnings;
use WJSON;

my $wjson = new WJSON;
$wjson->Array(
    ['A', 'B', 'C', 'D', 'E'],
    [1, 2, 3, 4, 5]
);
print $wjson->HeaderCGI;
print $wjson->Print;

retornara:

[
    ["A","B","C","D","E"],
    [1,2,3,4,5]
]

Exemplo 4

#!/usr/bin/perl

use strict;
use warnings;
use WJSON;

my $wjson = new WJSON;
$wjson->Object(
    {
        indice1 => 'valor1',
        indice2 => 'valor2',
        indice3 => 'valor3',
    },
    {
        indice4 => 'valor4',
        indice5 => 'valor5',
        indice6 => 'valor6',
    }
);
print $wjson->HeaderCGI;
print $wjson->Print;

retornara:

[
    {"indice1":"valor1","indice3":"valor3","indice2":"valor2"},
    {"indice6":"valor6","indice5":"valor5","indice4":"valor4"}
]

Exemplo 5

#!/usr/bin/perl

use strict;
use warnings;
use WJSON;

my $wjson = new WJSON;
$wjson->Object(
    {
        indice1 => 'valor1',
        indice2 => 'valor2',
        indice3 => 'valor3',
    },
    {
        indice4 => 'valor4',
        indice5 => 'valor5',
        indice6 => 'valor6',
    }
);
$wjson->Open('Foo');
    $wjson->Array(1, 2, 3, 4, 5);
$wjson->Close;
print $wjson->HeaderCGI;
print $wjson->Print;

retornara:

[
    {"indice1":"valor1","indice3":"valor3","indice2":"valor2"},
    {"indice6":"valor6","indice5":"valor5","Foo":[1,2,3,4,5],"indice4":"valor4"}
]

Com uma pequena mudança no código acima, setando um valor em Close:

$wjson->Close(1);

retornara:

[
    {"indice1":"valor1","indice3":"valor3","indice2":"valor2"},
    {"indice6":"valor6","indice5":"valor5","indice4":"valor4"},
    {"Foo":[1,2,3,4,5]}
]

Exemplo 6

#!/usr/bin/perl

use strict;
use warnings;
use WJSON;

my $wjson = new WJSON;
$wjson->Open('Baz');
    $wjson->Object(
        indice1 => 'valor1',
        indice2 => 'valor2',
        indice3 => 'valor3',
    );
    $wjson->Open('Foo');
        $wjson->Object(
            indice4 => 'valor4',
            indice5 => 'valor5',
            indice6 => 'valor6',
        );
        $wjson->Open('Bar');
            $wjson->Object(
                indice7 => 'valor7',
                indice8 => 'valor8',
                indice9 => 'valor9',
            );
        $wjson->Close;
    $wjson->Close;
$wjson->Close;
print $wjson->HeaderCGI;
print $wjson->Print;

retornara:

{
    "Baz": {
        "indice1": "valor1",
        "indice3": "valor3",
        "Foo": {
            "indice6": "valor6",
            "Bar": {
                "indice7": "valor7",
                "indice8": "valor8",
                "indice9": "valor9"
            },
            "indice5": "valor5",
            "indice4": "valor4"
        },
        "indice2": "valor2"
    }
}

Exemplo 7

#!/usr/bin/perl

use strict;
use warnings;
use WJSON;

my $wjson = new WJSON;
$wjson->Open('Baz');
    $wjson->Object(
        indice1 => 'valor1',
        indice2 => 'valor2',
        indice3 => 'valor3',
    );
    $wjson->Open('Foo');
        $wjson->Object(
            indice4 => 'valor4',
            indice5 => 'valor5',
            indice6 => 'valor6',
        );
        $wjson->Open('Bar');
            $wjson->Object(
                indice7 => 'valor7',
                indice8 => 'valor8',
                indice9 => 'valor9',
            );
        $wjson->Close(1);
    $wjson->Close(1);
$wjson->Close;
print $wjson->HeaderCGI;
print $wjson->Print;

retornara:

{
    "Baz": [{
        "indice1": "valor1",
        "indice3": "valor3",
        "indice2": "valor2"
    }, {
        "Foo": [{
            "indice6": "valor6",
            "indice5": "valor5",
            "indice4": "valor4"
        }, {
            "Bar": {
                "indice7": "valor7",
                "indice8": "valor8",
                "indice9": "valor9"
            }
        }]
    }]
}

Exemplo 8

#!/usr/bin/perl

use strict;
use warnings;
use WJSON;

my $wjson = new WJSON;
$wjson->Open('Baz');
    $wjson->Object(
        indice1 => 'valor1',
        indice2 => 'valor2',
        indice3 => 'valor3',
    );
    $wjson->Object(
        indice4 => 'valor4',
        indice5 => 'valor5',
        indice6 => 'valor6',
    );
    $wjson->Object(
        indice7 => 'valor7',
        indice8 => 'valor8',
        indice9 => 'valor9',
    );
$wjson->Close;
print $wjson->HeaderCGI;
print $wjson->Print;

retornara:

{
    "Baz": [{
        "indice1": "valor1",
        "indice3": "valor3",
        "indice2": "valor2"
    }, {
        "indice6": "valor6",
        "indice5": "valor5",
        "indice4": "valor4"
    }, {
        "indice7": "valor7",
        "indice8": "valor8",
        "indice9": "valor9"
    }]
}

Exemplo 9

#!/usr/bin/perl

use strict;
use warnings;
use WJSON;

my $wjson = new WJSON;
$wjson->Array(1,2,3,4,5);
$wjson->Array(6,7,8,9,10);
$wjson->Array('A','B','C','D','E');
$wjson->Array('F','G','H','I','J');
print $wjson->HeaderCGI;
print $wjson->Print;

retornara:

[
    [1, 2, 3, 4, 5],
    [6, 7, 8, 9, 10],
    ["A", "B", "C", "D", "E"],
    ["F", "G", "H", "I", "J"]
]

Exemplo 10

Usando variável javascript como referência do JSON

Perl

#!/usr/bin/perl

use strict;
use warnings;
use WJSON;

my $wjson = new WJSON;
$wjson->variable('json');
$wjson->Object(
    indice1 => 'valor1',
    indice2 => 'valor2',
    indice3 => 'valor3',
);
print $wjson->HeaderJSCGI;
print $wjson->Print;

HTML, mude o nome do "exemplo10.pl" para o nome do arquivo que você colocou no código acima

<!DOCTYPE html>

<html>
<head>
    <title>Exemplo 10</title>
    <script src="exemplo10.pl"></script>
    <script>
        window.onload = function(){
            alert('indice1: ' + json.indice1);
            alert('indice2: ' + json.indice2);
            alert('indice3: ' + json.indice3);
        };
    </script>
</head>

<body>

</body>
</html>

Exemplo 11

Exemplo primeiro do site http://json.org/example

#!/usr/bin/perl

use strict;
use warnings;
use WJSON;

my $wjson = new WJSON;
$wjson->Open('glossary');
    $wjson->Object(
        title => 'example glossary'
    );
    $wjson->Open('GlossDiv');
        $wjson->Object(
            title => 'S'
        );
        $wjson->Open('GlossList');
            $wjson->Object(
                GlossSee => 'markup'
            );
            $wjson->Open('GlossEntry');
                $wjson->Object(
                    ID => 'SGML',
                    SortAs => 'SGML',
                    GlossTerm => 'Standard Generalized Markup Language',
                    Acronym => 'SGML',
                    Abbrev => 'ISO 8879:1986',
                );
                $wjson->Open('GlossDef');
                    $wjson->Object(
                        para => 'A meta-markup language, used to create markup languages such as DocBook.'
                    );
                    $wjson->Open('GlossSeeAlso');
                        $wjson->Array('GML', 'XML');
                    $wjson->Close;
                $wjson->Close;
            $wjson->Close;
        $wjson->Close;
    $wjson->Close;
$wjson->Close;
print $wjson->HeaderCGI;
print $wjson->Print;

retornara:

{
    "glossary": {
        "GlossDiv": {
            "GlossList": {
                "GlossEntry": {
                    "GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
                        "GlossSeeAlso": ["GML", "XML"]
                    },
                    "GlossTerm": "Standard Generalized Markup Language",
                    "ID": "SGML",
                    "SortAs": "SGML",
                    "Acronym": "SGML",
                    "Abbrev": "ISO 8879:1986"
                },
                "GlossSee": "markup"
            },
            "title": "S"
        },
        "title": "example glossary"
    }
}

Exemplo 12

Exemplo segundo do site http://json.org/example

#!/usr/bin/perl

use strict;
use warnings;
use WJSON;

my $wjson = new WJSON;
$wjson->Open('menu');
    $wjson->Object(
        id => 'file',
        value => 'File',
    );
    $wjson->Open('popup');
        $wjson->Open('menuitem');
            $wjson->Object(
                {
                    value => 'New',
                    onclick => 'CreateNewDoc()'
                },
                {
                    value => 'Open',
                    onclick => 'OpenDoc()'
                },
                {
                    value => 'Close',
                    onclick => 'CloseDoc()'
                }
            );
        $wjson->Close;
    $wjson->Close;
$wjson->Close;
print $wjson->HeaderCGI;
print $wjson->Print;

retornara:

{
    "menu": {
        "value": "File",
        "popup": {
            "menuitem": [{
                "value": "New",
                "onclick": "CreateNewDoc()"
            }, {
                "value": "Open",
                "onclick": "OpenDoc()"
            }, {
                "value": "Close",
                "onclick": "CloseDoc()"
            }]
        },
        "id": "file"
    }
}

https://github.com/lucas1/WJSON

https://metacpan.org

http://www.perl.org

Deus é o limite!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.