gpt4 book ai didi

javascript - 从 json 数组转换为 json 对象无法正常工作

转载 作者:行者123 更新时间:2023-11-28 18:18:49 27 4
gpt4 key购买 nike

我创建了一个像这样的休息服务:

@GET
@Path("/getsummary")
@Produces("application/json")

public Response summary()
{

VoltDAOImpl voltDao = new VoltDAOImpl();
Map<String ,List<HashMap<String,String>>> returnList= voltDao.getOrderDetails("PEAKM" , "Hydra" ,
"" , voltDao.client,"notional" ,1000);
List<HashMap<String,String>> totalSlpSummaryList = returnList.get("total_slp_summary");
List<HashMap<String,String>> totalSlpSummaryBySideList = returnList.get("total_slp_summary_by_side");
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();

String json1 = null;
String json2 = null;
String json3 = null;
try {
json1 = ow.writeValueAsString(totalSlpSummaryList);
json2 = ow.writeValueAsString(totalSlpSummaryBySideList);
json3="["+json1+","+json2+"]";
//json3 = json1 + "\n" + json2;
System.out.println(json1);
System.out.println(json2);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


return Response.status(200).entity(json3).build();
}

然后我在 JavaScript 中使用它,如下所示:

var rootURL = "http://localhost:8181/RestServiceProject/rest/WebService/getsummary";
function findBySummary() {
console.log("inside loading grid");
var returnval1;
$.ajax({
type: 'GET',
url: rootURL,
dataType: "json",
async: false,
success: function(json3){

returnval1 = json3;
console.log(returnval1);

}

});
return returnval1;
}

console.log(returnval1);

返回以下结果: returnval1

稍后我调用 findBySummary(); 并执行以下操作:

    var json3 = findBySummary();

var json4 = json3[0];
console.log("json4");
console.log(json4);
var json_temp = JSON.stringify(json4);
console.log("json_temp")
console.log(json_temp);
var json_temp1 = json_temp[0];
console.log("json temp1");
console.log(json_temp1);

以下是此操作的日志输出: log output

我正在尝试转换 json_temp,即:

[{"total_exec_qty":"286595","total_notional":"21820771.72","total_wt_arr_last_slp":"2.4364","total_num_ords":"1630","total_wt_ivwap_slp":"6.0969","total_wt_arr_slp":"1.7889","total_ord_qty":"576991"}]

到此(json_temp1):

{"total_exec_qty":"286595","total_notional":"21820771.72","total_wt_arr_last_slp":"2.4364","total_num_ords":"1630","total_wt_ivwap_slp":"6.0969","total_wt_arr_slp":"1.7889","total_ord_qty":"576991"}

但是为什么我只得到 json_temp1 的[??

最佳答案

请注意,JSON.stringify(json4) 返回一个字符串。

因此,代码 json_temp[0] 将返回该字符串中的第一个元素。

你想要的是:

var json_temp1 = json4[0];

而不是:

var json_temp1 = json_temp[0];

下面的代码不符合您的需要:

var json_temp = JSON.stringify(json4);
console.log("json_temp")
console.log(json_temp);
var json_temp1 = json_temp[0];

关于javascript - 从 json 数组转换为 json 对象无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40309686/

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