inconsistant output from JSON.stringify
Sorry if this is repost but I couldn't find my question after I posted it. I have a rails app that is rendering a json string and storing the same sting in the db. The output from the initial page that receives the output and the page that displays the data from the db have different output. The data and the function to format the data are identical. I'm stumped.
function:
function prettyPrint(jsonStr) {
var jsonObj = jQuery.parseJSON(jsonStr);
return '<pre>' + JSON.stringify(jsonObj,null,'\t') + '</pre>';
}
data:
{"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"}]}
output 1: (from 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"
}
]
}
output 2: (from 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\"}]"
}
Both the "Devices" array and the "response_details" arrays are being encoded as strings rather than arrays. Find where this is happening in the code that is putting the data in the database and fix that.
I ended up formatting the output with 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>
精彩评论