1

I have an attribute field called "klantnaam". In another field called "adressen" I have a JSON array with several objects. In the object I have the following fields: adressoort, bedrijfsnaam and persoonsnaam. First I want to check if the object has the adressoort 2. If so then check if bedrijfsnaam is filled. If so show that. Is it empty check if persoonsnaam is filled. If so show that. If both bedrijfsnaam and persoonsnaam is empty then show the attribute klantnaam. I have the follow code but it is only showing the attribute field klantnaam even when for example bedrijfsnaam is filled. What do I miss.

<script runat="server">
  Platform.Load("Core","1");
  
  var adressenJSON = Attribute.GetValue("adressen"); // Veronderstel dat je de JSON-waarde ophaalt uit een attribuut
  var getJsonFieldValue = Platform.Function.ParseJSON(adressenJSON);
  
  var adressoort = getJsonFieldValue.adressoort;
  var bedrijfsnaam = getJsonFieldValue.bedrijfsnaam;
  var persoonsnaam = getJsonFieldValue.persoonsnaam;
  
  var klantnaam = Attribute.GetValue("klantnaam");
  var titelklant = "";
  
  if (adressoort == 2) {
    if (!bedrijfsnaam && !persoonsnaam) {
      titelklant = klantnaam;
    } else if (bedrijfsnaam) {
      titelklant = bedrijfsnaam;
    } else {
      titelklant = persoonsnaam;
    }
  } else {
    titelklant = klantnaam;
  }
  
  Variable.SetValue("@titelklant", titelklant);
</script>

%%=v(@titelklant)=%%
1
  • can you share an example of the JSON? If it is an array of objects, then what you have is not correct and is returning null as you would need to specify the index of the object in the array before you can call the key/value pairs in the object. Commented Jun 14, 2023 at 13:57

1 Answer 1

0

Judging from your description of the JSON, it sounds like you are using an array of objects and not just an object for your JSON. E.g.

[
  {"adressoort":"val1",
   "bedrijfsnaam": "val2",
   "persoonsnaam": "val3"
  },
  {"adressoort":"val4",
   "bedrijfsnaam": "val5",
   "persoonsnaam": "val6"
  }
]

In order to access the key/value pairs in the objects, you will need to reference the index of the object you want to use in the array.

E.g.

myArr[0].adressoort

I think this is the part you are missing in your example script. As a note, Arrays are 0 index, so 0 is the first object in the array, not 1.

You likely will also want to loop through the array to get each object, which can be done via a FOR loop pretty easily.

for (i=0;i<myArr.length();i++) {
  myArr[i].adressoort
}
1
  • 1
    Yes that was the missing piece! Thanks.
    – Martijn e
    Commented Jun 14, 2023 at 14:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .