[ABAP] String -> JSON

DATA: text TYPE string VALUE 'Hello world!'.

* ABAP (string) -> JSON
DATA(o_writer_json) = cl_sxml_string_writer=>create( type = if_sxml=>co_xt_json ).
CALL TRANSFORMATION id SOURCE text = text RESULT XML o_writer_json.
DATA(json) = cl_abap_codepage=>convert_from( o_writer_json->get_output( ) ).

WRITE: / json.

[ABAP] itab -> JSON

* Variante 1 (CALL TRANSFORMATION)
TYPES: BEGIN OF s_person,
         name  TYPE string,
         title TYPE string,
         age   TYPE i,
       END OF s_person.

TYPES: t_person TYPE STANDARD TABLE OF s_person WITH DEFAULT KEY.

DATA(it_persons) = VALUE t_person( ( name = 'Horst' title = 'Herr' age = 30 )
                                   ( name = 'Jutta' title = 'Frau' age = 35 )
                                   ( name = 'Ingo' title = 'Herr' age = 31 ) ).

* ABAP (iTab) -> JSON
DATA(o_writer_itab) = cl_sxml_string_writer=>create( type = if_sxml=>co_xt_json ).
CALL TRANSFORMATION id SOURCE values = it_persons RESULT XML o_writer_itab.
DATA: json TYPE string.
cl_abap_conv_in_ce=>create( )->convert( EXPORTING
                                          input = o_writer_itab->get_output( )
                                        IMPORTING
                                          data = json ).

WRITE: / json.

* Variante 2 (/ui2/cl_abap2json)
SELECT matnr, mtart, meins, pstat
  INTO TABLE @DATA(it_mara)
  FROM mara
  UP TO 10 ROWS.

* ABAP (iTab) -> JSON
DATA(o_conv) = NEW /ui2/cl_abap2json( ).
DATA(lv_str) = o_conv->table2json( it_data = it_mara ).

WRITE: / lv_str.

[ABAP] JSON -> itab

TYPES: BEGIN OF s_person,
         name  TYPE string,
         title TYPE string,
         age   TYPE i,
       END OF s_person.

TYPES: t_person TYPE STANDARD TABLE OF s_person WITH DEFAULT KEY.

DATA: json TYPE string VALUE '{"VALUES":[{"NAME":"Horst","TITLE":"Herr","AGE":30},{"NAME":"Jutta","TITLE":"Frau","AGE":35},{"NAME":"Ingo","TITLE":"Herr","AGE":31}]}'.
DATA(it_persons) = VALUE t_person( ).

* JSON -> ABAP (iTab)
CALL TRANSFORMATION id SOURCE XML json RESULT values = it_persons.

IF lines( it_persons ) > 0.
  WRITE: / it_persons[ 1 ]-name.
ENDIF.

[ABAP] itab -> JSON (trex)

TYPES: BEGIN OF s_person,
         name  TYPE string,
         title TYPE string,
         age   TYPE i,
       END OF s_person.

TYPES: t_person TYPE STANDARD TABLE OF s_person WITH DEFAULT KEY.

DATA(it_persons) = VALUE t_person( ( name = 'Horst' title = 'Herr' age = 30 )
                                   ( name = 'Jutta' title = 'Frau' age = 35 )
                                   ( name = 'Ingo' title = 'Herr' age = 31 ) ).

* ABAP (iTab) -> JSON (trex)
DATA(o_trex) = NEW cl_trex_json_serializer( it_persons ).
o_trex->serialize( ).

WRITE: / o_trex->get_data( ).

[JavaScript] String in JSON wandeln

Beispiel 1 (simpel)

// https://javascript.info/json

// JSON-Objekt definieren
let sJSON = '{ "name":"Heinz","age":"56","city":"Hamburg" }';

// JSON-Objekt aus String parsen
let oJSONpar = JSON.parse(sJSON);

// Testausgabe
console.log(oJSONpar.name);

Beispiel 2 (reviver)

// JSON-Objekt definieren
let sJSON = '{ "name":"Heinz","age":"56","city":"Hamburg","birth":"2018-04-25T12:00:00.000Z" }';

// JSON-Objekt aus String parsen
let oJSONpar = JSON.parse(sJSON, function(key, value) {

  // wenn Datumsfeld "birth"
  if (key == 'birth')
  {
      // Datumsobjekt zurückgeben
      return new Date(value);
  }
  else
  {
      return value;
  };
});

// Geburtsdatum ist jetzt vom Typ "Date" mit enspr. Funktionen
console.log(oJSONpar.birth.toLocaleString('de-DE'));

[JavaScript] JSON-Datei per HTTP-Request holen und parsen

// Link zur JSON-Datei
let sURL = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json';
// Request-Object
let request = new XMLHttpRequest();
// MIME-Typen
// txt: "text/plain"
// html: "text/html"
// json: "application/json"
request.overrideMimeType('application/json');
// Requestmethode
request.open('GET', sURL, true);
// Datentyp
request.responseType = 'text';
// Handler für asyncrone Antwort des Requests
// wenn Daten erfolgreich geladen
request.onload = function() {
  console.log('onload()');
  // gesamte Response ausgeben
  let sJSON = request.response;
  console.log(sJSON);
  
  // JSON-Daten parsen
  let oJSON = JSON.parse(sJSON);
  // Wert eines Attributes ausgeben
  console.log(oJSON.homeTown);
};
// bei Änderung des Ready-States
request.onreadystatechange = function () {
  console.log('onreadystatechange()');
  console.log(request.readyState);
  console.log(request.status);
  console.log(request.statusText);
};
// Request absenden
request.send();

[ABAP] XML nach JSON parsen

* XML-Daten
DATA(lv_xml) = |<object-><str name="text"->abcd</str-><bool name="flag"->true</bool-><member name="number"-><num->111</num-></member-><member name="content"-><null /-></member-></object->|.

TRY.
* XML-Daten lesen
    DATA(o_r) = cl_sxml_string_reader=>create( input = cl_abap_codepage=>convert_to( lv_xml ) ).
* evtl. Objektkomponenten mit <member->-Elementen darstellen
*    reader->set_option( if_sxml_reader=>co_opt_sep_member ).

    DATA(o_w) = CAST if_sxml_writer( cl_sxml_string_writer=>create( type     = if_sxml=>co_xt_json
                                                                    encoding = 'UTF-8' ) ).
* Ausgabeoptionen setzen
    o_w->set_option( option = if_sxml_writer=>co_opt_linebreaks ).
    o_w->set_option( option = if_sxml_writer=>co_opt_indent ).

    o_r->next_node( ).
* JSON parsen
    o_r->skip_node( o_w ).

* Ausgabe konvertieren
    DATA(lv_json) = cl_abap_codepage=>convert_from( CAST cl_sxml_string_writer( o_w )->get_output( ) ).

* JSON ausgeben
    cl_demo_output=>display_json( lv_json ).
  CATCH cx_root INTO DATA(e_txt).
    WRITE: / e_txt->get_text( ).
ENDTRY.