Using JSON Data with Coldfusion

前端 未结 2 837
旧巷少年郎
旧巷少年郎 2020-12-03 09:31

I\'ve worked with JSON data in the past - mainly \'fudging\' my way to a solution, and not really understanding why or how things work. I\'ve come across an issue where the

相关标签:
2条回答
  • 2020-12-03 09:53

    (This is really more of a comment, but is a bit too long ... )

    I've worked with JSON data in the past - mainly 'fudging' my way to a solution, and not really understanding why or how things work

    JSON strings are essentially just a representations of two objects:

    • arrays which are denoted by [] and
    • structures (or objects) which are denoted by {}

    Looking at the API string, the braces {} indicate you are dealing with a structure:

         { "theKey": "theValue" }
    

    In your case, the domain name is the structure key:

        { "domain.co.uk": "theValue" }
    

    .. and the value is a nested structure containing two static keys: "status" and "classkey"

        { "theKey":  {"status":"available","classkey":"thirdleveldotuk"}  }
    

    As with any structure, you can iterate through the keys dynamically using a for .. in loop, a collection loop if you prefer cfml.

         for (theKey in theStruct) {
             WriteDump( theKey ); // ie "domain.co.uk"
         }
    

    Then inside the loop use associative array notation to grab the value, ie:

         theStatus = theStruct[ theKey ]["status"]; // "available"
    
         // ... OR
         theValue  = theStruct[ theKey ]; 
         theStatus = theValue.status;
    

    That is all there is to it. You can use similar logic to access any type of nested structures.

    0 讨论(0)
  • 2020-12-03 10:04

    If you run this with deserializeJSON(data), you'll see that you just end up with structures with nested structures. So, you can loop through your struct, grab the keys and then grab that key's status. In JSON terms, your JSON object has nested objects.

    <cfset data = deserializeJSON(apiData) />
    <cfset formattedData = [] />
    <cfset tmp = {} />
    
    <cfloop collection=#data# item="domain">
        <cfset tmp.domain = domain />
        <cfset tmp.status = data[domain]["status"] />
        <cfset arrayAppend(formattedData,duplicate(tmp)) />
    </cfloop>
    
    <cfdump var=#formattedData# />
    
    0 讨论(0)
提交回复
热议问题