Its possible to use if/else using JSON?

Hello, I have a question that has relation with JSON, but I don’t see any category for that, so I put it in Javascript.

I have this json code:


Which works very well. My problem is when I fill everything its okay, but sometimes I don’t need to send the 2 files. Sometimes only 1, but if I let it empty any of the file/name values empty I get an error. I’m thinking on using if/else if the file URL/name is empty, don’t parse that part of the code.

Its possible to do that on json?

if you are using PHP you could do what i did (had a little help with it just the other day). Php json output - what am i doing wrong?

You basically use php to convert the json data to an array that you then have to loop through at which point you can get it to match things or omit things based on any variables you want to set. So you could look for a specific ‘name’ or ‘url’ in your case.


Thanks!! But im not using php :frowning:

How are you populating the JSON?

1 Like

No. JSON is a storage format and as such doesn’t know any logic. You would have to apply your if/else logic either on the code that creates the JSON (preferred) or the code that reads it.

1 Like

What do you mean with leaving it empty, and what kind of error? Both empty strings and null are be valid JSON values, but assuming your code loops over the attachment array, you’d actually omit the 2nd object altogether so that you don’t even have to check its values:

  "subject": "<Subject>",
  "attachment": [
    { "name": "<Filename_extension1>", "url": "<File_url1>" }
1 Like

Also an empty array is certainly valid.

“Dont parse that part of the code” is referring to the code at the other end of the transmission (JSON is a transmission/storage medium) So your problem is actually in the code that’s handling the JSON.

1 Like

If I understand you correctly, you want to get just certain parts of a JSON object and not all of them. If so then you should probably look up GraphQL.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.