动态解析JSON并使用输入复选框在html上打印关键值并获取选定键的新JSON [英] Parse JSON dynamically and print key values on html with input checkbox and get a new JSON of selected keys

查看:108
本文介绍了动态解析JSON并使用输入复选框在html上打印关键值并获取选定键的新JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图解析一个未知的JSON,其格式可能是任何东西。所以,我不知道访问它的钥匙。我想访问JSON中的每个键,并使用HTML在屏幕上打印出所有键和值。所以我做了一个递归函数来访问JSON中的每个键,并使用变量名html来打印键。
代码:



JSON字符串:

 FetchDetails:{
TransactionDetails:{
ServiceName:Airtel Mobile Bill Postpaid,
officeID:209,
BillAmount:931.00,
ConsumerName:Chetan Kumar Yadav,
consumerKeysValues:9352423664,
partPaymentAllow:1,
partPaymentType:Both,
lookUpId:6163298,
officeCodeValue:RATNC011
},
BillDetails:[{
LableName:到期日期之前的金额,
LableValue:931.00
},{
LableName:到期日,
LableValue:NA
},{
LableName:手机号码,
LableValue:9352423664
},{
LableName :到期日后的金额,
LableValue:931.00
},{
LableName:Bill Date,
LableValue:NA
},{
LableName:消费者名称,
LableValue:Chetan Kumar Yadav
},{
LableName:Bill Cycle,
LableValue: NA
,{
LableName:账单号,
LableValue:NA
},{
LableName:账户Number,
LableValue:1116231291
}]
}
}

通过代码访问Parsed JSON中的每个键

  function scan(info){
var sub_root = [];
if(info instanceof Object){
for(k in info){

if(info.hasOwnProperty(k)){
console.log('scanning财产'+ k);

if(info [k] instanceof Object){
me + =< div class ='root'>< div class ='sub_root'><输入类='node'name ='sub_root [+ k +]'value ='+ k +'type ='checkbox'/> + k;
console.log(k);
counter ++;
scan(info [k]);
me + =< / div>;
me + =< / div>;
} else {
me + =< div class ='json_check'>< input class ='node'name ='sub_root [+ y +] [+ k + ]'value ='+ k +'type ='checkbox'/> + k +:+ info [k] +< / div>;
scan(info [k]);
counter ++;
}
}
}
} else {
console.log('found value:'+ info);


$ b $ / code $ / pre
$ b $ p

在此之后,我能够访问JSON中的每个键,并将每个节点以嵌套形式打印,并在其前面带有复选框以选择任何节点/键。
下面是截图:



[问题解决]
现在在底部,我有一个提交按钮,当我点击它时,我想用它们的父节点形成一个JSON的检查值。所以就像我用一个值检查一个键,我应该得到它的父键。
例如:我在TransactionDetails中选择了ServiceName和officeID,并在BillDetails中选择了一些数组值,所以我应该得到类似这样的内容


$ b $

 FetchDetails:{
TransactionDetails:{
ServiceName:Airtel Mobile Bill Postpaid,
officeID:209
},
BillDetails:[{
LableName:截止日期前的金额,
LableValue:931.00
},{
LableName:截止日期,
LableValue:NA
},{
LableName:帐号,
LableValue: 1116231291
}]
}
}

为了得到这个JSON格式并遍历HTML对象,我写了这段代码:

 <$ c $ ('click',function(){

var solid ='{' ;
var input = $('input')。is(':checked');
if(input){
input = $('input');

$ b $('。node:checked')。each(function(index){
var parentEls = $(this).closest(input)
.map(function(){
solid + = this.value;
return this.value;
})
.get()
.join(, );

console.log(parentEls);

});
solid + ='}';

$(.submit_json).html(solid);
});


解决方案

您需要使用。父母(),而不是 .closest(),因此您可以获得所有包含的元素。



然后在必要时创建包含这些名称的属性。

  $(#btn_createservice)。 ()函数(){
var svc_obj = {};
$(。node:checked)。 ).parents(。node)。map(function(){
return this.value;
))。get()。reverse()。forEach(function(name){$ b $如果它不存在
cur_obj [name] = {};
}
cur_obj = cur_obj [name]; / /如果(!cur_obj [name]){ /用于下一次迭代;
});
var thisname = this.name.match(/ \ [([^ [])+ \] $ /)[1]; //从name =sub_root [...]获取属性名称
cur_obj [thisname] = this.value;
});
$(。submit_json)。html(JSON.stringify(svc_obj));
})

您需要修复您创建的HTML,以便复选框具有 value ='+ info [k]'


I am trying to parse an unknown JSON whose format could be anything. So, I dont know the keys to access it. I want to access every key in JSON and print out all keys and values on screen using HTML. So I made a recursive function to access every key in JSON and used a variable name html to print the keys. here`s the code:

JSON String:

{
    "FetchDetails": {
        "TransactionDetails": {
            "ServiceName": "Airtel Mobile Bill Postpaid",
            "officeID": "209",
            "BillAmount": "931.00",
            "ConsumerName": "Chetan Kumar Yadav",
            "consumerKeysValues": "9352423664",
            "partPaymentAllow": "1",
            "partPaymentType": "Both",
            "lookUpId": "6163298",
            "officeCodeValue": "RATNC011"
        },
        "BillDetails": [{
            "LableName": "Amount Before Due Date",
            "LableValue": "931.00"
        }, {
            "LableName": "Due Date",
            "LableValue": "NA"
        }, {
            "LableName": "Mobile Number",
            "LableValue": "9352423664"
        }, {
            "LableName": "Amount After Due Date",
            "LableValue": "931.00"
        }, {
            "LableName": "Bill Date",
            "LableValue": "NA"
        }, {
            "LableName": "Consumer Name",
            "LableValue": "Chetan Kumar Yadav"
        }, {
            "LableName": "Bill Cycle",
            "LableValue": "NA"
        }, {
            "LableName": "Bill Number",
            "LableValue": "NA"
        }, {
            "LableName": "Account Number",
            "LableValue": "1116231291"
        }]
    }
}

Heres the code to access every key in Parsed JSON

function scan(info) {
  var sub_root = [];
  if (info instanceof Object) {
    for (k in info) {

      if (info.hasOwnProperty(k)) {
        console.log('scanning property ' + k);

        if (info[k] instanceof Object) {
          me += "<div class='root'> <div class='sub_root'> <input class='node' name='sub_root[" + k + "]' value='" + k + "' type='checkbox' />" + k;
          console.log(k);
          counter++;
          scan(info[k]);
          me += "</div>";
          me += "</div>";
        } else {
          me += "<div class='json_check' ><input class='node' name='sub_root[" + y + "] [" + k + "]' value='" + k + "' type='checkbox' />" + k + ": " + info[k] + " </div>";
          scan(info[k]);
          counter++;
        }
      }
    }
  } else {
    console.log('found value : ' + info);

  }
}

After this, I am able to access every key in JSON and printed every node in a nested form with checkboxes in front of them to select any node/key. Here`s the screenshot:

[PROBLEM to be solved] Now at the bottom, I have a submit button, when I click on it I want to form a JSON of checked values with their parent nodes. So like if I check a key with a value, I should get its parent keys along with it. For example: I have selected ServiceName and officeID in TransactionDetails, and some array values in BillDetails, so I should get something like this

{
    "FetchDetails": {
        "TransactionDetails": {
            "ServiceName": "Airtel Mobile Bill Postpaid",
            "officeID": "209"
        },
        "BillDetails": [{
            "LableName": "Amount Before Due Date",
            "LableValue": "931.00"
        }, {
            "LableName": "Due Date",
            "LableValue": "NA"
        }, {
            "LableName": "Account Number",
            "LableValue": "1116231291"
        }]
    }
}

[EDITED] To get this JSON format and traverse through HTML objects I am writing this code:

$('#btn_createservice').on('click', function() {

        var solid = '{';
        var input = $('input').is(':checked');
        if(input){
            input = $('input');
        }

        $('.node:checked').each(function(index) {
            var parentEls = $(this).closest(input)
              .map(function() {
                  solid +=  this.value;
                return this.value;
              })
              .get()
              .join( ", " );

            console.log(parentEls);

        });
        solid += '}';

        $( ".submit_json" ).html(solid);
});

解决方案

You need to use .parents(), not .closest() so you get all the containing elements.

Then create containing properties with those names when necessary.

$("#btn_createservice").on("click", function() {
    var svc_obj = {};
    $(".node:checked").each(function() {
        var cur_obj = svc_obj;
        $(this).parents(".node").map(function () {
            return this.value;
        }).get().reverse().forEach(function(name) {
            if (!cur_obj[name]) { // create property if it doesn't already exist
                cur_obj[name] = {};
            }
            cur_obj = cur_obj[name]; // use this for next iteration;
        });
        var thisname = this.name.match(/\[([^[])+\]$/)[1]; // Get property name from name="sub_root[...]"
        cur_obj[thisname] = this.value;
    });
    $(".submit_json").html(JSON.stringify(svc_obj));
})

You need to fix the HTML you're creating so that the checkboxes have value='" + info[k] "'.

这篇关于动态解析JSON并使用输入复选框在html上打印关键值并获取选定键的新JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆