Google Chrome JSON.encode / decode array

So, I'm writing a little Greasemonkey Userscript and its working fine in Firefox however if I try to run it with Tampermonkey on Googles Chrome I get weird erros when encoding/decoding arrays.

I try to make the Script cross browser compatible so I had to write a function to decide which JSON methods to use

function jsonEncode(string) { 
  try {
    return JSON.stringify(string); 
  } catch (e) {
    return JSON.encode(string); 
  }
}

function jsonDecode(obj) {
  try { 
    return JSON.parse(obj); 
  } catch (e) { 
    return JSON.decode(obj);
  }
}

To simplify things I have now reduced the code to a simple array and the attempt to encode/decode and iterate

var array = ['string1', 'string2'];

var encoded = jsonEncode(array);
localStorage.setItem('json_test', encoded);

var decoded = jsonDecode(localStorage.getItem('json_test'));
for(var i = 0; i < decoded.length; i++) {
    console.log(decoded[i]); 
}

I expect the output to be

string1
string2

instead chrome gives me this

[
"
s
t
r
i
n
g
1
"
,
"
s
t
r
i
n
g
2
"
]

Does anyone have any idea how to solve this, or why chrome is doing that?

EDIT 1: Chrome Version 15.0.874.121 m

EDIT 2: have still not figured it out but when I try it with an object instead of an array it works so I will do it this way now, thanks for your time and help!

Answers


Open JS console in Chrome - this let's you set breakpoints in the loop - and add watches on variables.

Beside that jsonDecode doesn't decode - there's still the brackets...

The problem is that you decode to string as is seems - that why it slices the string in letters - just as you coded it.

JSON ordinary represents arrays ... maybe check the documentation for correct output parameters.


Need Your Help

Entity framework DateTime.Now - 7 days C#

c# .net entity-framework frameworks

I try to get the entries of my mssql table from the past 7 days with entity framework in c#.

db:migrate creates the file db/development.sqlite3

ruby-on-rails-3 sqlite rake postgis

db:migrate creates the file db/development.sqlite3 if the rails app uses sqlite. I prefer to use postgresql for development and production before deploying to heroku.