简体   繁体   中英

Json Returning [object object] instead of values

I am trying to extract the values of a json but when I return it I get an object object. Something I did wrong in decoding? this is the decoding code in php

<?php $contenido=file_get_contents("https://www.deperu.com/api/rest/cotizaciondolar.json");
$info = json_decode($contenido,true);   
$cadena=array(
        0=>$info['cotizacion'],
    );
    echo json_encode($cadena);      
?> 

this is the function code


<script>
    $(function() {
        $("#btnbuscar").on('click',function(){          

           var direccion='servicio.php';
            $.ajax({
                type:'get',
                url:direccion,

                success:function(datos){

                    var campo=eval(datos);

                    alert(datos[0]);

            }
            });
            return false;
        });
    });
</script>



Uwhen you write this:

$cadena=array(
    0=>$info['cotizacion'],
);
echo json_encode($cadena);

Your $info is an array, and cadena is an array, too. So you can direct point $cadenra to the array like this:

$cadena= $info['cotizacion'];
echo json_encode($cadena);

Or fix your js like this:

alert(datos[0][0]);

Here is a simple way to read your JSON without Ajax but with using $.getJSON

On your PHP file since you want to get only "cotization" data change: $cadena=array(0=>$info['cotizacion'] to $cadena=array(0=>$info['cotizacion'][0] and you can remove [0] if you are planning to have and to loop on multiple "cotizacion"

On your javascript use:

$.getJSON("servicio.php", function(data) {
  var items = [];
  $.each(data[0], function(key, val) {
    (key + '=' + val);
  });
});

There are several solutions, but don't get wrong in a javascript/jquery while calling a json chain.

For example:

<?php
// Page : service.php
$json = '{
    "service": "Reference dollar exchange rate",
    "website": "website.com",
    "link": "https://www.website.com/gearbox_type/",
    "quotation": [{
        "buy": 3.419,
        "sale": 3.424
    }]
}';
// $json = file_get_contents("https://www.website.com/api/example.json");
$info = json_decode($json,true); // convert array
$cadena=array(
    0=>$info['quotation'][0],
);
echo json_encode($cadena); // convert json
// get-> [{"buy":3.419,"sale":3.424}]
echo json_encode($cadena[0]); // convert json
// get-> {"buy":3.419,"sale":3.424}
?>

// Javascript 
// To better use your function I would have to do a cleanup of the code with JSON.parse
<script>
    $(function() {

        /*
         * Check yes and Json and convert json string
         * Analyze the data with JSON.parse () and the data becomes a JavaScript object.
         * Ex. var obj = '{hello:'mitico'}' -> convert object
         * $.clean_string_json(obj) return-> {hello:'mitico'}
         * $.clean_string_json('text' + obj) return-> {}
         * $.clean_string_json('text' + obj,false) return-> false
         * $.clean_string_json('text' + obj,true) return-> true
         */
        $.clean_string_json = function (str,xreturn) {
            try {
                return JSON.parse(str);
            } catch (e) {
                return xreturn === false ? false : xreturn || {};
            }
        };

        $("#btnbuscar").on('click',function(){          
            $.ajax({
                type:'get',
                url: 'service.php',
                success:function(datos){
                    var campo= $.clean_string_json(datos);
                    alert(datos[0]); // return -> {"buy":3.419,"sale":3.424}
                }
            });
            return false;
        });
    });
</script>

Welcome to stackoverflow . We hope you like it here.

As already pointed out by @Anurag Srivastava, call the url directly and you'll get json back, you do not need a proxy.

 const jUrl = "https://www.deperu.com/api/rest/cotizaciondolar.json"; $.get(jUrl).then(({cotizacion}) => console.log(cotizacion));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM