Search code examples
jsonstructcoldfusioncfml

Extract JSON data from struct in struct


See the output of a deserializeJSON(query).

enter image description here

For each row, how i can extract only id and DTIME? Following is my code:

 <cfscript>
  record=deserializeJSON(query_testing.data_test);

  writeDump(record);

</cfscript>

Below is a sample data in "query_testing.data_test":

 '{"id3":
        {"DECISION":1,
        "DTIME":"2013-10-18 16:17:28"},
   "id5":
        {"DECISION":1,
        "DTIME":"2013-10-09 15:43:35",}
  }'

Solution

  • <cfscript>
    
        record = deserializeJSON(query_testing.data_test);
    
        rows = [];
        for (id in record) {
    
            rows.add({
                id:    reReplace(id, "^id", ""),
                dtime: record[id].DTIME
            });
        }
        writeDump(rows);
    
    </cfscript>
    

    Here's the tag variant and a usage example as requested:

    <cfset record = deserializeJSON(query_testing.data_test)>
    
    <cfset rows = []>
    <cfloop collection="#record#" item="id">
    
        <cfset rows.add({
            id:    reReplace(id, "^id", ""),
            dtime: record[id].DTIME
        })>
    </cfloop>
    <cfdump var="#rows#">
    
    <!--- print as table --->
    <cfoutput>
        <table>
            <tr>
                <th>id</th>
                <th>dtime</th>
            </tr>
            <cfloop array="#rows#" index="row">
                <tr>
                    <td>#encodeForHtml(row.id)#</td>
                    <td>#dateTimeFormat(row.dtime, "yyyy-mm-dd, HH:nn:ss")#</td>
                </tr>
            </cfloop>
        </table>
    </cfoutput>