简体   繁体   English

json_decode不解释数组

[英]json_decode not interpreting array

I have a following JSON string, arriving via AJAX to server: 我有一个以下JSON字符串,通过AJAX到达服务器:

{"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] $data = json_decode(stripslashes($_POST['data']), true); $data['Names'][0] I don't get 'asdasd' as I wanted, but "[" symbol. $data = json_decode(stripslashes($_POST['data']), true); $data['Names'][0]我没有得到'asdasd',但是"["符号。 Where the problem lies? 问题出在哪里?

PS JS code, sending JSON string: PS JS代码,发送JSON字符串:

            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 :) 正在发送的mt变量与案例完全无关:)

The string is encoded incorrectly. 字符串编码不正确。 $data['Names'] is a string, so by accessing [0] you'll get the first character. $ data ['Names']是一个字符串,所以通过访问[0]你将获得第一个字符。

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. 如果你再次json_decode $ data ['Names']你应该得到一些工作,虽然也实际上是错误的ecoded(作为一个数字索引而不是数组的对象。)我很确定严格的json解析器将失败内串。

I'd suggest fixing whatever generates it, rather than on the decoding side. 我建议修复任何产生它的东西,而不是解码方面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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