Skip to main content
WolfShade
Legend
January 10, 2018
Question

Loop through JSON string - not using DeserializeJSON()

  • January 10, 2018
  • 2 replies
  • 2311 views

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 has been closed for replies.

    2 replies

    birdy1980
    Participant
    January 23, 2018

    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.

    Inspiring
    January 10, 2018

    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

    WolfShade
    WolfShadeAuthor
    Legend
    January 10, 2018

    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,

    ^ _ ^

    Inspiring
    January 10, 2018

    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