gpt4 book ai didi

javascript - 解析 JSON 将每个逗号替换为
元素 Javascript

转载 作者:行者123 更新时间:2023-12-01 03:58:12 27 4
gpt4 key购买 nike

我有一串 JSON 数据,我需要将每个逗号替换为 <br>在 JavaScript 中。

这是我的 JSON {"Items":"beans ,rice ,flour","Quantity":"4 ,5 ,6"}

还有我的 JSON 调用

jQuery(document).ready(function($) {
$.get( url, function( data ) {

$.each( data, function( i, val ) {

$( "#pantry" ).append(
'<h3>' +
'<p>' +
items +
'</p>' +
'<p>' +
val +
'</p>' +
'</h3>'
);
});
});
});

我需要添加什么作为修饰符?

最佳答案

您可以对 JSON 对象进行字符串化,然后对字符串使用方法replace

var test = JSON.stringify({"Items":"beans ,rice ,flour","Quantity":"4 ,5 ,6"});

var updatedTest = test.replace(/,/g, '<br>');
// Outputs:
// {"Items":"beans <br>rice <br>flour"<br>"Quantity":"4 <br>5 <br>6"}

但这不会正确工作,因为它会更新分隔每个属性的逗号。

这更符合逻辑:

var test = JSON.parse(JSON.stringify({"Items":"beans ,rice ,flour","Quantity":"4 ,5 ,6"}));
var updatedTest = {};
for (prop in test){
updatedTest[prop] = test[prop].replace(/,/g, '<br>')
}

updatedTest = JSON.stringify(updatedTest);

// updadedTest Outputs:
// {"Items":"beans <br>rice <br>flour","Quantity":"4 <br>5 <br>6"}

关于javascript - 解析 JSON 将每个逗号替换为 <br> 元素 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42445771/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com