Skip to content

Instantly share code, notes, and snippets.

@antelio
Forked from RiverSongFox/itab_to_json.abap
Last active August 29, 2015 14:11
Show Gist options
  • Save antelio/a4fe3a5436a30b430a1c to your computer and use it in GitHub Desktop.
Save antelio/a4fe3a5436a30b430a1c to your computer and use it in GitHub Desktop.
ITAB_TO_JSON
*&---------------------------------------------------------------------*
*& Form ITAB_TO_JSON
*&---------------------------------------------------------------------*
* Get JSON representation of any plain internal table
*----------------------------------------------------------------------*
FORM itab_to_json USING it_abap TYPE STANDARD TABLE
CHANGING et_json TYPE string.
DATA : lo_object_info TYPE REF TO cl_abap_structdescr
, lw_attribute_info TYPE abap_compdescr.
DATA : lv_attributes TYPE string
, lv_objects TYPE string
, lv_first_attribute TYPE abap_bool
, lv_first_object TYPE abap_bool.
FIELD-SYMBOLS : <fs_object> TYPE ANY
, <fs_attribute> TYPE ANY.
lv_first_object = abap_true.
LOOP AT it_abap ASSIGNING <fs_object>.
lo_object_info ?= cl_abap_typedescr=>describe_by_data( <fs_object> ).
lv_first_attribute = abap_true.
LOOP AT lo_object_info->components INTO lw_attribute_info.
ASSIGN
COMPONENT lw_attribute_info-name
OF STRUCTURE <fs_object>
TO <fs_attribute>.
IF lv_first_attribute = abap_false.
CONCATENATE lv_attributes `, ` INTO lv_attributes.
ELSE.
lv_first_attribute = abap_false.
ENDIF.
CONCATENATE lv_attributes
`"` lw_attribute_info-name `" : `
`"` <fs_attribute> `"`
INTO lv_attributes.
ENDLOOP.
IF lv_first_object = abap_false.
CONCATENATE lv_objects `, ` INTO lv_objects.
ELSE.
lv_first_object = abap_false.
ENDIF.
CONCATENATE lv_objects ` { ` lv_attributes ` } `
INTO lv_objects.
CLEAR : lv_attributes.
ENDLOOP.
CONCATENATE `[` lv_objects `]` INTO et_json.
ENDFORM. "itab_to_json
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment