Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 如何将html文本转换为有组织的json数组?_Jquery_Json - Fatal编程技术网

Jquery 如何将html文本转换为有组织的json数组?

Jquery 如何将html文本转换为有组织的json数组?,jquery,json,Jquery,Json,我有两个html分区,我需要以特定的方式循环遍历它们的html和格式 //Desired output { "nameoffirstcategory" : {a , b, c, d, e, f}, "nameofsecondcategory" : {a , b , c ,d ,e,f} } 这是两个复选框列的html <h5>Preview</h5> <div class="row"&g

我有两个html分区,我需要以特定的方式循环遍历它们的html和格式

//Desired output

    { 
    "nameoffirstcategory" : {a , b, c, d, e, f},
    "nameofsecondcategory" : {a , b , c ,d ,e,f} 
    }
这是两个复选框列的html

      <h5>Preview</h5>
              <div class="row">
                 <div class="col tms-check-column">
                    <label class="informationTitle" id="topic-preview-left">Topic Example Left</label>
                    <div id="p-example-left">
                    </div>
                 </div>
                 <div class="col tms-check-column">
                    <label class="informationTitle" id="topic-preview-right">Topic Example Right</label>
                    <div id="p-example-right">
                    </div>
                 </div>
              </div>
           </div>
           <div class="modal-footer">
              <p class="tms-autosaved-txt">AutoSaved</p>
              <button onclick="saveAllItems();" type="button" class="btn btn-secondary">Auto Save</button>
              <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
           </div>
在这里,我很好地循环了各个列,得到了我需要的所有数据。问题是json输出的格式与上面所需的输出不一样

    // my javascript function

    function saveAllItems() {

        let values = [];

        titlel = jQuery("#topic-preview-left").text();
        titler = jQuery("#topic-preview-right").text();

        values.push({
            titlel: titlel
        });

        // left column text
        jQuery("#p-example-left > p").each(function() {

            let check = jQuery(this).html();
            values.push({
                check: check
            });

        });

        values.push({
            titler: titler
        });


        // right column text
        jQuery("#p-example-right > p").each(function() {
            let check = jQuery(this).html();

            values.push({
                check: check
            });
        });

        let json = JSON.stringify(values);
        console.log(json);


    }

使用对象并将值添加到对象中,而不是值数组。 在向对象添加项时,首先检查键的值是否未定义(如果未使用逗号追加到现有值,则可以是字符串),如下所示。 此外,如果它可以是数组,我们可以将值推送到属性

比如:

 var values = {};

 if(values.title1){
   values.title1 =  values.title1 + ',' +title1;
  }
else{
  values.title1 = title1;
}

 // if array then,

var values = {};

 if(values.title1 && values.title1.length > 0 ){
   values.title1.push(title1)
  }
else{
  values.title1 = [title1];
}

按check属性时也是如此。

根据问题中提供的HTML,您可以遍历
标签
s,并从下一个
div
元素获取文本。如下图所示:-

$(function() {
    const data = $('[id*="topic-preview-"]').map(function(index, elem) {
        return {
            [$(this).attr('id').replace(/-/g, '')]: $(this).next().text().trim()
        }
    }).get();
    console.log(JSON.stringify(data));
});
$(函数(){
常量数据=$('[id*=“主题预览-”]).map(函数(索引,元素){
返回{
[$(this).attr('id').replace(/-/g',)]:$(this.next().text().trim())
}
}).get();
log(JSON.stringify(data));
});

主题示例左
项目清单
主题示例右
项目清单

您可以使用嵌套循环来完成,如下所示:

函数saveAllItems(){
var值={};
jQuery(“[id*=主题预览]”)。每个(函数(){
var$items=jQuery(“div[id*=p-example]>p”,$(this.parent());
值[jQuery(this).text()]=$items.map(函数(){
返回jQuery(this.text();
}).get();
});
console.log(值);
}
saveAllItems()

主题示例左
a

b

c

d

主题示例右 g


好的,根据您的要求,我尝试按您的要求创建结构,并修改代码,以便您能够轻松理解


输出:

{…}
​
"
Topic Example Left  
": Array [ "Topic Example Left", "Medicaid" ]
​
"
Topic Example right  
": Array [ "Topic Example right", "Active duty military" ]
​
JSFIDLE的链接:


看一看,如果什么都不懂,让我知道,我会根据你的内容解释一些,你到底想要什么“同时发生精神和药物滥用的人},{“检查”:“现役军人”}
这就是你想要的还是不想要的?我需要json格式。我不知道怎么做。{“category left title”:{item1,item2,item3},“category right title”:{item1,item2,item3}}这是一个很好的答案,它正是我运行代码时想要的工作方式。唯一的问题是,当我在我的html上运行它时,它会返回这个{“付款”:[],“特别计划”:[],“左动态五”:[“现金或自付”,“Medicaidd”,“Medicare”,],“右动态三”:[“同时患有精神和药物滥用障碍的人”,“患有饮食障碍的人”]}好的,那么您有其他元素具有相同的类。可能此选择器将与其他元素不匹配?
jQuery([id*=topic preview]”。每个(…
<div id="topic-preview-left">
Topic Example Left  
</div>
<div id="p-example-left">
<p>Topic Example Left</p>
<p>Medicaid</p>
</div>
<div id="topic-preview-right">
Topic Example right  
</div>
<div id="p-example-right">
<p>Topic Example right</p>
<p>Active duty military</p>
</div>
   var leftKey  = $("#topic-preview-left").text();
var rightKey = $("#topic-preview-right").text();

var pLeftExamples = [];
  $("#p-example-left > p").each(function() {
            pLeftExamples.push($(this).html());
        });
var pRightExamples = [];
$("#p-example-right > p").each(function() {
  pRightExamples.push($(this).html());
});    

var mainObject = {};
mainObject[leftKey] = pLeftExamples;
mainObject[rightKey] = pRightExamples;
console.log(mainObject);
{…}
​
"
Topic Example Left  
": Array [ "Topic Example Left", "Medicaid" ]
​
"
Topic Example right  
": Array [ "Topic Example right", "Active duty military" ]
​