Получение значений из нескольких структур и массивов с помощью Coldfusion

У меня есть вызов API, который получает результаты опроса от третьей стороны. Затем я DeserializeJSON результат, и это выглядит так (nb-структуры в questionResults были минимизированы для пространства):

введите описание изображения здесь

Затем я перебираю первый уровень и могу получить значения первого уровня (например, идентификатор устройства и т. Д.), Однако не могу найти способ получения данных questionResults. В частности, мне нужны переменные questionText и resultValue. (в рамках questionResults всегда есть 11 результатов массива, каждый с одинаковыми структурами установки)

В настоящее время я использую следующий код:

<cfhttp url="#myurl#" method="POST" result="myresult">
  <cfhttpparam type="URL" name="apiKey" value="#apiKey#">
  <cfhttpparam type="URL" name="SurveyId" value="#SurveyId#">       
</cfhttp>

<cfset recordData=DeserializeJSON(#myresult.filecontent#)>

<cfdump var="#recordData#">

<cfloop from="1" to="#ArrayLen(recordData)#" index="i">
   <cfoutput>
     <strong>Record ID:</strong> #recordData[i].id#<br>

      <cfloop from="1" to="#ArrayLen(recordData[i])#" index="j">
            #recordData[i][j]#<br>
      </cfloop>
   </cfoutput>
   <hr> 
 </cfloop>

Но получите ошибку "Struct не может быть использован как массив"

Любой совет, как получить данные, которые я ищу?

3 ответа

Я думаю, что когда вы просматриваете структуры, массивы или почти все остальное, синтаксис сценария гораздо проще визуализировать.

ПРИМЕЧАНИЕ: я не могу получить доступ к своим спискам, чтобы сохранить их для TryCF прямо сейчас.

Во-первых, я устанавливаю свое значение "JSON":

<cfscript>

myresult.filecontent = '[
    {
        deviceIdentifier: "asdf" ,
        deviceName : "localiPad1" ,
        id : "23155736" ,
        otherStuff : "adsfasdfasd" ,
        questionResults : [
            {
                answerDate : "2018-04-26T09:25:55:55.0000000" ,
                questionIdentifier : "G8N9" ,
                questionText : "Select User" ,
                questionType : "Text" ,
                resultValue : "Beatriz Pinho"
            } ,
            {
                answerDate : "2018-04-26T09:25:55:55.0000000" ,
                questionIdentifier : "2" ,
                questionText : "Question2" ,
                questionType : "Text" ,
                resultValue : "Answer2"
            } ,
            {
                answerDate : "2018-04-26T09:25:55:55.0000000" ,
                questionIdentifier : "3" ,
                questionText : "Question3" ,
                questionType : "Text" ,
                resultValue : "Answer3"
            } ,
            {
                answerDate : "2018-04-26T09:25:55:55.0000000" ,
                questionIdentifier : "4" ,
                questionText : "Question4" ,
                questionType : "Text" ,
                resultValue : "Answer4"
            } ,
            {
                answerDate : "2018-04-26T09:25:55:55.0000000" ,
                questionIdentifier : "5" ,
                questionText : "Question5" ,
                questionType : "Text" ,
                resultValue : "Answer5"
            } ,
            {
                answerDate : "2018-04-26T09:25:55:55.0000000" ,
                questionIdentifier : "6" ,
                questionText : "Question6" ,
                questionType : "Text" ,
                resultValue : "Answer6"
            } ,
            {
                answerDate : "2018-04-26T09:25:55:55.0000000" ,
                questionIdentifier : "7" ,
                questionText : "Question7" ,
                questionType : "Text" ,
                resultValue : "Answer7"
            } ,
            {
                answerDate : "2018-04-26T09:25:55:55.0000000" ,
                questionIdentifier : "8" ,
                questionText : "Question8" ,
                questionType : "Text" ,
                resultValue : "Answer8"
            } ,
            {
                answerDate : "2018-04-26T09:25:55:55.0000000" ,
                questionIdentifier : "9" ,
                questionText : "Question9" ,
                questionType : "Text" ,
                resultValue : "Answer9"
            } ,
            {
                answerDate : "2018-04-26T09:25:55:55.0000000" ,
                questionIdentifier : "10" ,
                questionText : "Question10" ,
                questionType : "Text" ,
                resultValue : "Answer10"
            } ,
            {
                answerDate : "2018-04-26T09:25:55:55.0000000" ,
                questionIdentifier : "11" ,
                questionText : "Question11" ,
                questionType : "Text" ,
                resultValue : "Answer11"
            } 
        ] ,
        moreOtherStuff : "asdfasdfasdfasd"
    } ,
    {
        deviceIdentifier: "fdsa" ,
        deviceName : "localiPad2" ,
        id : "2" ,
        otherStuff : "adsfasdfasd" ,
        questionResults : [
            {
                answerDate : "2018-04-26T09:25:55:55.0000000" ,
                questionIdentifier : "G8N9" ,
                questionText : "Select User" ,
                questionType : "Text" ,
                resultValue : "Silent Bob"
            } ,
            {
                answerDate : "2018-04-26T09:25:55:55.0000000" ,
                questionIdentifier : "2" ,
                questionText : "Question2" ,
                questionType : "Text" ,
                resultValue : "Answer2"
            } ,
            {
                answerDate : "2018-04-26T09:25:55:55.0000000" ,
                questionIdentifier : "3" ,
                questionText : "Question3" ,
                questionType : "Text" ,
                resultValue : "Answer3"
            } ,
            {
                answerDate : "2018-04-26T09:25:55:55.0000000" ,
                questionIdentifier : "4" ,
                questionText : "Question4" ,
                questionType : "Text" ,
                resultValue : "Answer4"
            } ,
            {
                answerDate : "2018-04-26T09:25:55:55.0000000" ,
                questionIdentifier : "5" ,
                questionText : "Question5" ,
                questionType : "Text" ,
                resultValue : "Answer5"
            } ,
            {
                answerDate : "2018-04-26T09:25:55:55.0000000" ,
                questionIdentifier : "6" ,
                questionText : "Question6" ,
                questionType : "Text" ,
                resultValue : "Answer6"
            } ,
            {
                answerDate : "2018-04-26T09:25:55:55.0000000" ,
                questionIdentifier : "7" ,
                questionText : "Question7" ,
                questionType : "Text" ,
                resultValue : "Answer7"
            } ,
            {
                answerDate : "2018-04-26T09:25:55:55.0000000" ,
                questionIdentifier : "8" ,
                questionText : "Question8" ,
                questionType : "Text" ,
                resultValue : "Answer8"
            } ,
            {
                answerDate : "2018-04-26T09:25:55:55.0000000" ,
                questionIdentifier : "9" ,
                questionText : "Question9" ,
                questionType : "Text" ,
                resultValue : "Answer9"
            } ,
            {
                answerDate : "2018-04-26T09:25:55:55.0000000" ,
                questionIdentifier : "10" ,
                questionText : "Question10" ,
                questionType : "Text" ,
                resultValue : "Answer10"
            } ,
            {
                answerDate : "2018-04-26T09:25:55:55.0000000" ,
                questionIdentifier : "11" ,
                questionText : "Question11" ,
                questionType : "Text" ,
                resultValue : "Answer11"
            } 
        ] ,
        moreOtherStuff : "asdfasdfasdfasd"
    }
]' ;

Я создал переменную JSON, которая имитирует то, что вы получаете из вашего http-запроса. Затем я буду десериализовать JSON из этого.

recordData = deserializeJSON(myresult.filecontent) ;

Что дает мне хороший массив со структурами и другими массивами в нем.

Это та часть, которую я нахожу намного проще в сценарии.

for ( var i IN recordData ) {  // loop through the outer array

    writeOutput("<strong>Record ID:</strong>" & i.id & "<br>") ;

    for ( var j IN i.questionResults ) { // loop through each questionResults
        writeOutput(
            j.questionIdentifier & " - " & 
            j.questionText
            &  " >> " & 
            j.resultValue 
            & " ------- " &
            j.answerDate
            & "<br>"
        ) ;
    }
}

И закрой мой скрипт.

</cfscript>

Если бы я мог заставить мой код TryCF.com отображаться правильно, вы бы увидели следующее:

Record ID:23155736
G8N9 - Select User >> Beatriz Pinho ------- 2018-04-26T09:25:55:55.0000000
2 - Question2 >> Answer2 ------- 2018-04-26T09:25:55:55.0000000
3 - Question3 >> Answer3 ------- 2018-04-26T09:25:55:55.0000000
4 - Question4 >> Answer4 ------- 2018-04-26T09:25:55:55.0000000
5 - Question5 >> Answer5 ------- 2018-04-26T09:25:55:55.0000000
6 - Question6 >> Answer6 ------- 2018-04-26T09:25:55:55.0000000
7 - Question7 >> Answer7 ------- 2018-04-26T09:25:55:55.0000000
8 - Question8 >> Answer8 ------- 2018-04-26T09:25:55:55.0000000
9 - Question9 >> Answer9 ------- 2018-04-26T09:25:55:55.0000000
10 - Question10 >> Answer10 ------- 2018-04-26T09:25:55:55.0000000
11 - Question11 >> Answer11 ------- 2018-04-26T09:25:55:55.0000000
Record ID:2
G8N9 - Select User >> Silent Bob ------- 2018-04-26T09:25:55:55.0000000
2 - Question2 >> Answer2 ------- 2018-04-26T09:25:55:55.0000000
3 - Question3 >> Answer3 ------- 2018-04-26T09:25:55:55.0000000
4 - Question4 >> Answer4 ------- 2018-04-26T09:25:55:55.0000000
5 - Question5 >> Answer5 ------- 2018-04-26T09:25:55:55.0000000
6 - Question6 >> Answer6 ------- 2018-04-26T09:25:55:55.0000000
7 - Question7 >> Answer7 ------- 2018-04-26T09:25:55:55.0000000
8 - Question8 >> Answer8 ------- 2018-04-26T09:25:55:55.0000000
9 - Question9 >> Answer9 ------- 2018-04-26T09:25:55:55.0000000
10 - Question10 >> Answer10 ------- 2018-04-26T09:25:55:55.0000000
11 - Question11 >> Answer11 ------- 2018-04-26T09:25:55:55.0000000

ПРИМЕЧАНИЕ: я запускаю это в Люси. ACF не нравится мой анализ JSON, и я не стал копать его, чтобы найти, какой символ ему не нравится. Это все еще работает, хотя.:-)

У вас есть массив структур, и один из элементов структуры - это другой массив структур с именем questionResults. Я предлагаю такой подход.

<cfloop array="#recordData#" index="ThisStructure">
do the easy stuff 
<cfif StructkeyExists(ThisStructure, "questionResults">
loop through that array and process it
closing tags

From your sample code it looks like you are referencing the same initial array in your second loop. That looks wrong to me. Попробуйте это вместо этого.

<cfloop from="1" to="#ArrayLen(recordData)#" index="i">
    <cfoutput>
        <strong>Record ID:</strong> #recordData[i].id#<br>

        <cfloop from="1" to="#ArrayLen(recordData[i].questionResults)#" index="j">
            <cfdump var="#recordData[i].questionResults[j]#">
        </cfloop>
    </cfoutput>
    <hr> 
</cfloop>

Я изменил это <cfloop from="1" to="#ArrayLen(recordData[i])#" index="j"> к этому <cfloop from="1" to="#ArrayLen(recordData[i].questionResults)#" index="j">

Обновить

In response to your comment, I updated my code example by changing this code #recordData[i][j]#<br> к этому коду <cfdump var="#recordData[i].questionResults[j]#"> as you cannot just simply output complex values as the error you reported stated.

You should be able to reference the questionText data (and other elements) like this #recordData[i].questionResults[j].questionText#,

Другие вопросы по тегам