How to handle potentially "false" inputs in JSON? Discussion of alternatives
P粉161939752
P粉161939752 2023-09-10 09:35:21
0
2
545

Suppose, I'm not sure if the selected authorities exist (but if they do, I want them selected). If there are no authorities selected, I want jQuery to select the authorities regardless of whether they are selected (actually, this means retrieving the value of the hidden input). My thoughts on using JS's "true value"/"false value" concept to handle this situation are:

    let user = {
        id: $(this).find('[name=id]').val(),
        username: $(this).find('[name=username]').val(),
        password: $(this).find('[name=password]').val(),
        name: $(this).find('[name=name]').val(),
        lastName: $(this).find('[name=lastName]').val(),
        department: $(this).find('[name=department]').val(),
        salary: $(this).find('[name=salary]').val(),
        age: $(this).find('[name=age]').val(),
        email: $(this).find('[name=email]').val(),
        enabledByte: $(this).find('[name=enabledByte]').val(),
        authorities: JSON.parse($(this).find('[name=authorities]:checked').val()) || 
                    JSON.parse($(this).find('[name=authorities]').val())
    };

However, it doesn't work. Interestingly, it does work in the code snippet below. Isn't the undefined returned by val() when the match fails a "false value"? think about it! My best guess is that JSON.parse() throws an error when undefined is parsed, rather than returning some "false value" as I would expect. This method doesn't accept "param OR param", right?

How do you think I should provide a fallback for this situation (besides, of course, checking the selected authorities individually for a "false value", which is a bit verbose for me) ?

 

<头>
<元字符集=“UTF-8”>


<标题>Management Page

<正文>
<标题> name Surname department e-mail <正文>

Fill in the form

<表格>
<标签=“名称”>name:
<脚本> $(document).ready(function() { $('form').on('submit', asynchronous function (event) { event.preventDefault(); $('tbody').append( `` ); const SubmitButton = $(this).find('[type=submit]'); Constant form = $(this); Submit button.removeClass('btn-primary') .addClass('btn-success') .attr('value', 'User has been added!') .attr('type', 'button') .click(() => $('[href="#users-table"]').tab('show')); setTimeout(function(){ commitButton.removeClass('btn-success') .addClass('btn-primary') .attr('value', 'submit') .attr('Type
P粉161939752
P粉161939752

reply all(2)
P粉818306280

The problem is that if the selector doesn't find any matches, .val() returns undefined, while JSON.parse(undefined) throws an exception .

Execute the fallback in the parameter list of JSON.parse() so that you will parse any value that is successfully obtained.

authorities: JSON.parse($(this).find('[name=authorities]:checked').val() || 
                        $(this).find('[name=authorities]:first').val())
P粉561323975

Depending on your use case, you have several options:

  1. You can combine JSON.parse like this. This will make it fall back to other strings before parsing, so it won't error if the first value is undefined. However, this will result in an error if both values ​​are undefined or one of them is invalid JSON.
JSON.parse($(this).find('[name=authorities]:checked').val()) || $(this).find('[name=authorities]').val());
  1. If you know that the values ​​are either valid JSON or undefined, you can fall back to null. null is a valid JSON value and can be parsed. However, if any of the values ​​are invalid JSON, an error will still occur.
JSON.parse($(this).find('[name=authorities]:checked').val()) || $(this).find('[name=authorities]').val() || null);
  1. If there is a chance that either value is invalid JSON, you can surround it in a try/catch block. This way, even if it is invalid, no error will be thrown. This is the safest option and will never go wrong.
// Helper to make it easier to do this inline
function safeJsonParse(string) {
  try {
    return JSON.parse(string);
  } catch {
    // JSON is invalid. Will implicitly return undefined.
  }
}

safeJsonParse($(this).find('[name=authorities]:checked').val()) || safeJsonParse($(this).find('[name=authorities]').val())
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
John U.S. Department of Energy IT john_d@gmail.com
simple U.S. Department of Energy human Resources jane_d@gmail.com
${$(this).find('[name=name]').val()} ${$(this).find('[name=last-name]').val()} ${$(this).find('[name=department]').val()} ${$(this).find('[name=email]').val() || 'Not applicable'}