Skip to main content
WolfShade
Legend
Jan 10, 2018 3:52 PM UTC
Question

Loop through JSON string - not using DeserializeJSON()

Hello, all,

Is it possible for ColdFusion to iterate JSON data (stringify()) without parsing it to a JSON object using DeserializeJSON()?

V/r,

^ _ ^

PS:  Specifically if I have a JSON string like..

[{"name":"whichForm","value":"NDOD"},{"name":"caseNumber","value":"123"},{"name":"airLiner-0[]","value":"AIR"},{"name":"airLiner-0[]","value":"LINER"}]

I need to iterate this and get name/value pairs, without using DeserializeJSON(). 

    This topic is closed to new replies. Start a new post to keep the conversation going.

    5 replies

    birdy1980
    Participant
    Jan 23, 2018 10:51 AM UTC

    Hi,

    Maybe you could use a regular expression to get the name-value pairs? something along the way:

    var sRegex = """name"":""(.+?)"".+?""value"":""(.+?)""";
    var sJSONstring = "[{""name"":""whichForm"",""value"":""NDOD""},{""name"":""caseNumber"",""value"":""123""},{""name"":""airLiner -0[]"",""value"":""AIR""},{""name"":""airLiner-0[]"",""value"":""LINER""}]";
    var aMatches = sJSONstring.reMatchNoCase(sRegex);
    writedump(aMatches);

    Then split the aMatches strings using various list functions. Or  you could use reFindNoCase to get the subgroups.

    Translate
    Inspiring
    Jan 10, 2018 4:02 PM UTC

    I'm sure you could build a string parser, but deserializeJSON() is useful in two ways:

    1. It ensures that the string sent as JSON is indeed valid JSON, something your string parser would struggle with, and

    2. I'd be willing to bet it has less overhead than any string parser you'd write.

    I'd say deserializeJSON() is the proper tool for the job.

    -Nic

    Translate
    WolfShade
    WolfShadeAuthor
    Legend
    Jan 10, 2018 4:08 PM UTC

    Hi, Nic,

    Yes, it would, unfortunately for the application that I'm working on, it's destroying data that I need.

    I'm using jQuery to serializeArray() a form.  One of the form fields is a series of checkboxes.  Even turning it into an array by naming it "airLiner-0[]" (which can be cloned, so there could also be "airLiner-1[]" and "airLiner-2[]"), DeserializeJSON() converts that to an associative array, which eliminates duplicates - so only the last checked value is set (ie, "airLiner-0[]" = "AIR", "airLiner-0[]" = "Liner", but only "Liner" is set because it overwrites the first set.)

    So, I need to be able to iterate the JSON string, not a JSON object, in order to get all values.

    V/r,

    ^ _ ^

    Translate
    Inspiring
    Jan 10, 2018 4:21 PM UTC

    Perhaps use JSON.stringify() on individual form fields instead (if you are posting via AJAX).  Alternatively, you could $('myForm').serialize() on submit.  The focus needs to be on getting good data to the CFML backend that it can use, not trying to manage it using list parsing, which is fragile and could fail.

    -Nic

    Translate