var oJSON = [ {businessNum:2,merchantBusinessId:456}, {businessNum:1,merchantBusinessId:154}, {businessNum:3,merchantBusinessId:336}, {businessNum:5,merchantBusinessId:108} ];
制一个函数 fn(json); 出来如一下这种形式(字符串):
"[{\"amount\":\"1\",\"merbusinessId\":\"92\"},{\"amount\":\"1\",\"merbusinessId\":\"94\"},{\"amount\":\"1\",\"merbusinessId\":\"107\"}]"
补充问题:
原属数据:
oJSON = [{ brandName: "", businessCode: "0b489a6d-9844-4f0e-a977-d5bb983d36e5", businessName: "内饰清洁", businessNum: 2, id: null, merchantBusinessId: 95, merchantId: 34, price: 300, privilegePrice: 0, shoppingCarDetialsId: 659, totalCurrentPrice: null, totalNum: null, totalPrice: null, userId: 439, }, { brandName: "", businessCode: "0b489a6d-9844-4f0e-a977-d5bb983d36e5", businessName: "内饰清洁", businessNum: 1, id: null, merchantBusinessId: 108, merchantId: 34, price: 300, privilegePrice: 0, shoppingCarDetialsId: 659, totalCurrentPrice: null, totalNum: null, totalPrice: null, userId: 439, }, { brandName: "", businessCode: "0b489a6d-9844-4f0e-a977-d5bb983d36e5", businessName: "内饰清洁", businessNum: 5, id: null, merchantBusinessId: 666, merchantId: 34, price: 300, privilegePrice: 0, shoppingCarDetialsId: 659, totalCurrentPrice: null, totalNum: null, totalPrice: null, userId: 439, }]; //取 businessNum 和 merchantBusinessId 字段
看你是不是在做题,或者题目有要求。没有要求就是json。stringdify完事。
如果是要考你实现json字符串的序列化。那就麻烦一点。
类似伪代码:
fn(json){
var result='';
if array.isarray(json) result='[]';
else
result='{}'
for (var item in json){
if(json[item] is array or object)
result="${item}":${fn(json[item])}
}
else
result="${item}":${json[item] is bool?true or false; is string "json[item]"; is numer?json[item]}
}
如果数字不需要加引号,可以采用下面的方法
JSON.stringify(JSON.stringify(oJSON));
感谢回复, 可能需要fn(json); 出来形式和题目一模一样,只是数字变了..
@Coca-code: 搞定了
JSON.stringify(JSON.stringify(oJSON, function(k,v){ return isNaN(v) ? v : v.toString() }));
@dudu: 这个方法好,学习了
@dudu: 这方法NB,可能是我题目描述不准确,现在补了.
感谢
function transJson(json){
let res=JSON.stringify(json).replace(/"/g,"\"");
return res;
}
传入的json数字能先自行转为字符串不
感谢回复。 不是要都答案。
generatorServiceParam(shoppingCartDetails){ let newJson = [] for(let [index, json] of shoppingCartDetails.entries()){ for(let key in json){ if(newJson[index] == undefined){ newJson[index] = {} } if(key == 'businessNum' || key == 'merchantBusinessId'){ newJson[index][key] = json[key] + '' } } } newJson = JSON. //... };
fn(oJSON){ let newJson = [] for(let [index, json] of oJSON.entries()){ for(let key in json){ if(newJson[index] == undefined){ newJson[index] = {} } if(key == 'businessNum' || key == 'merchantBusinessId'){ newJson[index][key] = json[key] + '' } } } newJson = JSON.stringify(newJson) newJson = newJson.replace(/"/g, '\\"') return `"${newJson}"` };
点错了,这个函数可以满足要求!!~