How to JSON decode array elements in JavaScript?

前端 未结 7 516
盖世英雄少女心
盖世英雄少女心 2020-11-30 08:40

I have a JavaScript array that, among others, contains a URL. If I try to simply put the URL in the page (the array is in a project involving the Yahoo! Maps API) it shows t

相关标签:
7条回答
  • 2020-11-30 09:12
    eval('(' + jsonObject + ')')
    
    0 讨论(0)
  • 2020-11-30 09:13

    If you get this text in an alert:

    function(){return JSON.encode(this);}
    

    when you try alert(myArray[i]), then there are a few possibilities:

    • myArray[i] is a function (most likely)
    • myArray[i] is the literal string "function(){return JSON.encode(this);}"
    • myArray[i] has a .toString() method that returns that function or that string. This is the least likely of the three.

    The simplest way to tell would be to check typeof(myArray[i]).

    0 讨论(0)
  • 2020-11-30 09:24

    Suppose you have an array in PHP as $iniData with 5 fields. If using ajax -

    echo json_encode($iniData);
    

    In Javascript, use the following :

    <script type="text/javascript">
        $(document).ready(function(){
            $.ajax({
                type: "GET",
                url: "ajaxCalls.php",
                data: "dataType=ini",
                success: function(msg)
                {
                    var x = eval('(' + msg + ')');
                    $('#allowed').html(x.allowed);              // these are the fields which you can now easily access..
                    $('#completed').html(x.completed);
                    $('#running').html(x.running);
                    $('#expired').html(x.expired);
                    $('#balance').html(x.balance);
                }
            });
        });
    </script>
    
    0 讨论(0)
  • 2020-11-30 09:25

    JSON decoding in JavaScript is simply an eval() if you trust the string or the more safe code you can find on http://json.org if you don't.

    You will then have a JavaScript datastructure that you can traverse for the data you need.

    0 讨论(0)
  • 2020-11-30 09:30

    I decode JSON this way:

    eval( 'var from_json_object = ' + my_json_str + ';' );
    
    0 讨论(0)
  • 2020-11-30 09:32

    If the object element you get is a function, you can try this:

    var url = myArray[i]();
    
    0 讨论(0)
提交回复
热议问题