-3

I have an array like:

myarray['field1'] = "content of field1";
myarray['field2'] = "content of field2"; 

if I do console.log(myarray) I get:

myarray = [ field1 : "content of field1", field2 : "content of field2" ]

so I would transform to JSON so I tried to JSON.stringify(myarray) but it didn't worked... what I could have missed?

Thanks in advance! Cheers Luigi

Tim
  • 41,901
  • 18
  • 127
  • 145
Luigino
  • 745
  • 3
  • 7
  • 26
  • 1
    First of all... its not an `array`. It is a `map` ( or `object` in JavaScript ). Second... `JSON.stringify( whatever )` will always work as long as `whatever` is anything valid in JavaScript. What was the error that you were getting... ? – sarveshseri Mar 10 '15 at 09:12
  • have a look at this [POST](http://stackoverflow.com/questions/2295496/convert-array-to-json) – Braj Mar 10 '15 at 09:12
  • 1
    Is this `JavaScript` ? because your choice of identifier `myarray` for a map-like thing suggests that you are using `php`. – sarveshseri Mar 10 '15 at 09:15
  • it's in Javascript: starting from var myarray = []; I try to do console.log(myarray) I get [field1: "content1", field2: "content2"] then I try console.log(JSON.stringify(myarray)); and I get [] – Luigino Mar 10 '15 at 09:20

2 Answers2

0

Here is a php function I think might work for you:
function raw_json_encode($input) {

return preg_replace_callback(
    '/\\\\u([0-9a-zA-Z]{4})/',
    function ($matches) {
        return mb_convert_encoding(pack('H*',$matches[1]),'UTF-8','UTF-16');
    },
    json_encode($input)
);

}

it returns a string in JSON format.

0

Solved by myself.... I had just to declare myarray as:

var myarray = {};

so everything worked in this way. Thanks anyway to all!! Cheers Luigi

Luigino
  • 745
  • 3
  • 7
  • 26