Sorry if I've explained this wrong but I've got an object which is an array and I'm trying to get the fields to output but all I'm getting is [object object]
$.getJSON( "https://service1.homepro.com/smart.asmx/GetFAP_ProfileReviewsJSON?bid=141772&sort=1&page=1", function( data ) {
// console.log(data);
xmlText = data;
var jsonObj = x2js.xml_str2json( xmlText );
// console.log(jsonObj.SMART);
var html = '<div class="review">';
$.each( jsonObj, function( key, answer ) {
// console.log('key', key);
console.log('answer', answer);
html += '<div>' + answer + '</div>';
// html += '<div>' + key + '</div>';
});
$('div').html(html);
});
Can anyone help or show me where I've gone wrong?
Thanks
In JavaScript [object object]
is the default string representation of a JavaScript object
if it isn't null
or undefined
, you can see in the JavaScript toString() Reference that:
Every object has a
toString()
method that is automatically called when the object is to be represented as a text value or when an object is referred to in a manner in which a string is expected . By default, thetoString()
method is inherited by every object descended fromObject
. If this method is not overridden in a custom object,toString()
returns "[object type]
", where type is the object type. The following code illustrates this:
var o = new Object();
o.toString(); // returns [object Object]
Note: Starting in JavaScript 1.8.5 toString() called on null returns [object Null], and undefined returns [object Undefined], as defined in the 5th Edition of ECMAScript and a subsequent Errata. See Using_toString()_to_detect_object_class.
Solution:
object
you need to write a custom function that will do it for you by producing a custom representation of your object based on its properties. JSON.stringify(answer)
it will return your object as a string but I don't think it will give you the output you want to see. Is this what you need?
$.getJSON( "https://service1.homepro.com/smart.asmx/GetFAP_ProfileReviewsJSON?bid=141772&sort=1&page=1", function( data ) { var xmlText = data, x2js = new X2JS(), jsonObj = x2js.xml_str2json( xmlText ), html = '<div class="review">'; $.each( jsonObj.SMART.XMLJSON, function( key, answer ) { html += '<div><strong>' + answer.RefName + '</strong> - ' + answer.Testimonial + '</div>'; }); $('body').html(html); });
div { margin: 10px 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/x2js/1.2.0/xml2json.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You have to iterate through jsonObj.SMART.XMLJSON
, not jsonObj
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.