简体   繁体   中英

json_decode not interpreting array

I have a following JSON string, arriving via AJAX to server:

{"Names":"[{0:'asdasd'}]","Values":"[{0:'ad'}]"}

As you see, Names and Values were intended to hold an array. Problem is, when I call $data = json_decode(stripslashes($_POST['data']), true); $data['Names'][0] $data = json_decode(stripslashes($_POST['data']), true); $data['Names'][0] I don't get 'asdasd' as I wanted, but "[" symbol. Where the problem lies?

PS JS code, sending JSON string:

            var arr_names = "[";
        names.each(function(i){
            arr_names += "{" + i + ":'" + $(this).val() + "'}";
            if (i < names.length-1) arr_names += ",";
        });
        arr_names += "]";

        var arr_val = "[";
        values.each(function(i){
            arr_val += "{" + i + ":'" + $(this).val() + "'}";
            if (i < values.length-1) arr_val += ",";
        });
        arr_val += "]";

        var el = { "Names" : arr_names, "Values" : arr_val };
        el = encodeURIComponent(JSON.stringify(el));

        $.ajax({
            type:"POST",
            dataType:"html",
            data:"m=1&t="+type+"&data="+el,
            url:plugin_path+"option-proc.php",
            success: function(rsp){
                $("#result").html(rsp);
            }
        });

names and values are a bunch of text fields, selected by the class. m and t variables being sent, are completely irrelevant to the case :)

The string is encoded incorrectly. $data['Names'] is a string, so by accessing [0] you'll get the first character.

If you also json_decode $data['Names'] again you should get something working, although also that is actually incorrectly ecoded (as an object with numeric indexes rather than an array.) I'm pretty sure strict json parsers will fail on that inner-string.

I'd suggest fixing whatever generates it, rather than on the decoding side.

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