Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have an some PHP that looks like this:

$exec[0] = shell_exec("cat /etc/msm.conf | grep JAR_PATH");

$exec[1] = shell_exec("msm server list");
    if(strstr($exec[1],'[ ACTIVE ] "mc-srv" is running. Everything is OK.') !== FALSE){
        $exec[1] = 'mc online';
    }else{
        $exec[1] = 'mc offline';
    }

$exec[2] = shell_exec("sudo ts status");
    if($exec[2] == 'Server is running'){
        $exec[2] = 'ts online';
    }else{
        $exec[2] = 'ts ofline';
    }
echo json_encode($exec,JSON_FORCE_OBJECT);

An AJAX request gets sent to the page and the json is returned. If I use console.log(JSON.parse(data)) I see this in the console Object {0: "DEFAULT_JAR_PATH="server.jar"↵", 1: "mc online", 2: "ts ofline"} however I can not access any of its methods even if i use an associative array.

but If i create a new object and print that to the console it (in chrome atleast) looks exactly the same in terms of syntax highlighting exect I can access it via obj.method.

What am I doing wrong here?

share|improve this question
 
I don't see json_encode anywhere in your php... –  David McMullin Mar 17 at 15:48
 
"however I can not access any of its methods" - apart from that not being methods, but simple properties - what have you tried to access those? –  CBroe Mar 17 at 15:51
 
@DavidMcMullin Sorry I forgot to copy that part >.> `echo json_encode($exec,JSON_FORCE_OBJECT);'. –  wezternator Mar 17 at 16:15
 
@CBroe I have tried data.1 (as well as using ab and c in an assoc array so data.a), and data[1]. but the latter as excepted returned the character at position x thanks –  wezternator Mar 17 at 16:16
 
D'oh! You don't want to access data - that's still a simple text string and nothing more - but the parsed result instead, the object that JSON.parse returned. –  CBroe Mar 17 at 16:19
add comment

1 Answer

Based on how the object is being output in the console, it looks like it's being parsed okay by JSON.parse and is valid.

In which case, you should be able to access each method like this:

var obj = JSON.parse(data);
console.log( obj['0'] ); // returns "DEFAULT_JAR_PATH="server.jar""
console.log( obj['1'] ); // returns "mc online"

obj.0 won't work in this case because the method names are numbers.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.