简体   繁体   English

如何使用 AJAX 调用以漂亮的 UI 格式打印 JSON 数组

[英]How to print JSON array with AJAX call in a pretty format for UI

I am trying to validate data in a modal.我正在尝试以模式验证数据。 If there is an error, an alert box is displayed.如果出现错误,则会显示警告框。 I am getting the output of the API in this format:我以这种格式获取 API 的输出:

[{"Column":"ReportId","Result":"Invalid","Value":"repTest"}, 
{"Column":"Category","Result":"Invalid","Value":"testing"}]

I want to make it more readable to the user.我想让它对用户更具可读性。 How to get an output something like this in the alert box:如何在警报框中获得类似这样的输出:

ReportId is invalid due to repTest由于 repTest,ReportId 无效
Category is invalid due to testing ( or any custom string between the corresponding values)由于测试(或相应值之间的任何自定义字符串),类别无效

  $.ajax({
        type: 'POST',
        url: 'validate_report',
        contentType: 'application/json',
        data: JSON.stringify(AddreportRepoFinalObj),
        success: function (data) {
            if(data.indexOf('Failure') > -1){
                var e=JSON.stringify(data);
                pwIsf.alert({msg:'Failure'+e ,type:'error'});   
            }
            else if(data.indexOf('Success')>-1) 
            {
                document.getElementById('btn_addUpdate').removeAttribute('disabled')
                pwIsf.alert({msg:'Valid',type:'info'}); 
                $(validAddRepbtn).off();      
            }
            else{
                var a=data;                            // I want to access the value part here from the data. Like I want to get rcaReportID, Invalid and repTest only and not column result and value
               pwIsf.alert({msg:a, type:'error'}); 
            }
        },


    })

Assuming that data in the final if condition in your example is a JSON string then you first need to parse it to an array of objects.假设示例中最终if条件中的data是 JSON 字符串,那么您首先需要将其解析为对象数组。 From there you can loop through it and build your string output:从那里你可以遍历它并构建你的字符串输出:

 let data = '[{"Column":"ReportId","Result":"Invalid","Value":"repTest"},{"Column":"Category","Result":"Invalid","Value":"testing"}]' let arr = JSON.parse(data); var message = arr.map(o => `${o.Column} is ${o.Result} due to ${o.Value}`).join('\\r\\n'); console.log(message);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM