很抱歉,如果这是重新发布,但我发布后无法找到我的问题。我有一个rails应用程序,它呈现一个json字符串并在db中存储相同的sting。接收输出的初始页面的输出和显示db的数据的页面具有不同的输出。格式化数据的数据和功能是相同的。我很难过。
功能:
function prettyPrint(jsonStr) {
var jsonObj = jQuery.parseJSON(jsonStr);
return '<pre>' + JSON.stringify(jsonObj,null,'\t') + '</pre>';
}
数据:
{"Account":{"account_id":1},"response_details":[],"return_code":200,"Devices":[{"imei":"1234","name":"Device 1"},{"imei":"54321","name":"device 3"},{"imei":"354476024650842","name":"device 4 [no data]"},{"imei":"55124","name":"BlackBerry (8800)"},{"imei":"1234567890","name":"Garmin Sample"},{"imei":"987654321","name":"Second Garmin"},{"imei":"546787545678","name":"Tower 1"}]}
输出1 :(来自ajax)
{
"Account": {
"account_id": 1
},
"response_details": [],
"return_code": 200,
"Devices": [
{
"imei": "1234",
"name": "Device 1"
},
{
"imei": "54321",
"name": "device 3"
},
{
"imei": "354476024650842",
"name": "device 4 [no data]"
},
{
"imei": "55124",
"name": "BlackBerry (8800)"
},
{
"imei": "1234567890",
"name": "Garmin Sample"
},
{
"imei": "987654321",
"name": "Second Garmin"
},
{
"imei": "546787545678",
"name": "Tower 1"
}
]
}
输出2 :(来自db)
{
"Account": {
"account_id": 1
},
"response_details": "[]",
"return_code": 200,
"Devices": "[{\"imei\": \"1234\", \"name\": \"Device 1\"}, {\"imei\": \"54321\", \"name\": \"device 3\"}, {\"imei\": \"354476024650842\", \"name\": \"device 4 [no data]\"}, {\"imei\": \"55124\", \"name\": \"BlackBerry (8800)\"}, {\"imei\": \"1234567890\", \"name\": \"Garmin Sample\"}, {\"imei\": \"987654321\", \"name\": \"Second Garmin\"}, {\"imei\": \"546787545678\", \"name\": \"Tower 1\"}]"
}
答案 0 :(得分:0)
“Devices”数组和“response_details”数组都被编码为字符串而不是数组。在将数据放入数据库并修复它的代码中查找发生这种情况的位置。
答案 1 :(得分:0)
我最后使用ruby格式化输出
<% response = JSON.load(@order.response) %>
<% main_counter = 1 %>
<pre>
{
<% response.each do |k,v| -%>
<% if v.is_a?(Hash) %>
<%=k%>: {
<% counter = 1 %>
<% v.each do |k2,v2| -%>
<%=k2%>: <%=v2.to_json%><% if counter < v.size %>,<%end%>
<% counter += 1 %>
<%end%>
}<% if main_counter < response.size %>,<%end%>
<% elsif v.is_a?(Array) %>
<%=k%>: [
<% counter = 1 %>
<% v.each do |v2| -%>
<%=v2.to_json%><% if counter < v.size %>,<%end%>
<% counter += 1 %>
<%end%>
]<% if main_counter < response.size %>,<%end%>
<%else%>
<%=k%>: <%=v%><% if main_counter < response.size %>,<%end%>
<%end%><% main_counter += 1 %>
<%end%>
}
</pre>