5

Ok..so i have a json string (myJson) that looks like this:

{"id": "1", "file": "test.jpg"} 

and in my jquery function, I want to put these id and file values of my json string to an item in an array.

so, i have

var myArray = new Array();
var parsedJson = $.parseJSON(myJson);
myArray['item1']['id'] = parsedJson.id;
myArray['item1']['file'] = parsedJson.file;

but even after the execution of these codes, the length of the array myArray remains zero. Could somebody explain me why this is happening?

2
  • first of all this is not multidimensional array..this is basic json string Commented Apr 19, 2011 at 10:00
  • yeah...but i want to put the values from the parsed JSON string into a multidimensional array. Commented Apr 19, 2011 at 10:06

4 Answers 4

5

Perhaps you're confusing PHP associative arrays with JavaScript arrays. In JavaScript, you have objects instead of associative arrays and they behave differently. You can try one of the following approaches depending on your needs:

var myArray = {};
var parsedJson = $.parseJSON('{"id": "1", "file": "test.jpg"}');
myArray['item1'] = {};
myArray['item1']['id'] = parsedJson.id;
myArray['item1']['file'] = parsedJson.file;
myArray['item2'] = {};
myArray['item2']['id'] = parsedJson.id + '_2';
myArray['item2']['file'] = parsedJson.file + '_2';
console.log(myArray);

Or this:

var myArray = [];
var parsedJson = $.parseJSON('{"id": "1", "file": "test.jpg"}');
myArray.push({
    id: parsedJson.id,
    file: parsedJson.file
});
myArray.push({
    id: parsedJson.id + '_2',
    file: parsedJson.file + '_2'
});
console.log(myArray);
Sign up to request clarification or add additional context in comments.

1 Comment

I will give these a try ..thank you very much for your reply. I am very new to javascript.:)
1

You code can be rewritten simply like this

myArray['item1'] = {"id": "1", "file": "test.jpg"};

This code will produce the sample result.

You got the length of "myArray" = 0 because in this case, "item1" is a property of object myArray. It is not an element of myArray.

Please read this for more information about "Objects as associative arrays" http://www.quirksmode.org/js/associative.html

Comments

0

try

var obj = jQuery.parseJSON('{"id": "1", "file": "test.jpg"}');
alert( obj.id );
alert (obj.file)

DEMO

Comments

0

this works perfectly:

var obj = jQuery.parseJSON('{"id": "1", "file": "test.jpg"}');
alert( obj.id );
alert (obj.file);

but it breaks down when i send a multidimensional array created in php, the code i´m using is written below:

(jquery)

function actualizarIndex(){ 
    /* RECOGEMOS LAS VARIABLES */
    $.post('php/consulta-actualizar-index.php', 
        { arriendoConsulta: 'arriendo'}
        ,
        function(data) {
            var parsedJson = $.parseJSON(data);
            alert(parsedJson);
            alert(parsedJson.tipoInmueble);

        }).error(
            function(){
        console.log('Error al ejecutar la petición');
        }
    );

}

(php)

$actArriendo = $_POST["arriendoConsulta"];

//insertamos el inmueble con todas las opciones recbidas
$sql = "SELECT * FROM `recomendados-integridad` WHERE `negocio`= '$actArriendo'";
$inmueble = mysql_query($sql, $conexion) or die(mysql_error());

$i = 0;

if ($row = mysql_fetch_array($inmueble)){ 

   do { 
        echo "<hr><br>conteo: " . $i ."<br>";
        ${'camposInmuebleInicio'.$i} = array(
            'tipoInmueble' => $row['tipoInmueble'],
            'negocio' => $row['negocio'],
            'alcobas' => $row['alcobas'],
            'banos' => $row['banos'],
        );

        ++ $i;
       } 
       while ($row = mysql_fetch_array($inmueble)); 


} else { 
echo "¡ No se ha encontrado ningún registro !"; 
}


$casasArriendoArray = array( $camposInmuebleInicio0 ,  $camposInmuebleInicio1 , $camposInmuebleInicio2);
$json = json_encode( $casasArriendoArray );
echo $json;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.