7

Here's my array (from Chrome console):

array in Chrome console

Here's the pertinent part of code:

console.log(hours);
var data = JSON.stringify(hours);
console.log(data);

In Chrome's console I get [] from the last line. I should get {'Mon':{...}...}

Here is the minimal amount of JavaScript to reproduce the issue:

var test = [];
test["11h30"] = "15h00"
test["18h30"] = "21h30"
console.log(test);    
console.log(JSON.stringify(test)); // outputs []

I tried some other stuff like Convert array to JSON or Convert javascript object or array to json for ajax data but the problem remains.

Community
  • 1
  • 1
Eat Salad
  • 99
  • 1
  • 1
  • 6
  • Could you make a live example on jsfiddle.net for example? – leopik Feb 13 '15 at 13:38
  • 2
    where do you get Hours from? It doesn't seem like a js array, it seems more like an object.. – satchcoder Feb 13 '15 at 13:38
  • 4
    You have an object masquerading as an array there - the `length` says zero and the properties are named. – Jamiec Feb 13 '15 at 13:40
  • 3
    It looks like you've created arrays (`[]`) when you actually need objects (`{}`). In JavaScript if you want to use non-numerical keys (e.g. "11h30") you'll need to use an object instead. – JJJ Feb 13 '15 at 13:40
  • Possible duplicate of [passing an array to json.stringify](http://stackoverflow.com/questions/8943737/passing-an-array-to-json-stringify), though the answers there don't go into great detail about *why* an object is necessary versus an array. – apsillers Feb 13 '15 at 13:45
  • That said, some other data structure would probably be more suitable: for example an array of objects (`{ open: "11h30", close: "15h00" }`). Using key-value pairs for opening and closing hour respectively is a bit cumbersome. – JJJ Feb 13 '15 at 13:50
  • @Juhana I tried, but you can't use the same property for two or more values .. or i have to use an array, and after this, how do you know which 'open' comes with which 'close' ... (tell me if i'm not understandable) – Eat Salad Feb 13 '15 at 14:00

4 Answers4

32

Here is the minimal amount of javascript to reproduce the issue

var test = [];
test["11h30"] = "15h00"
test["18h30"] = "21h30"
console.log(test);    
console.log(JSON.stringify(test)); // outputs []

The issue with the above is that, while javascript will be happy to let you late-bind new properties onto Array, JSON.stringify() will only attempt to serialize the actual elements in the array.

A minimal change to make the object an actual object, and JSON.stringify works as expected:

var test = {}; // here is thre only change. new array ([]) becomes new object ({})
test["11h30"] = "15h00"
test["18h30"] = "21h30"
console.log(test);
console.log(JSON.stringify(test)); // outputs {"11h30":"15h00","18h30":"21h30"}
Jamiec
  • 133,658
  • 13
  • 134
  • 193
3

Like all JavaScript objects, Arrays can have properties with string-based keys like the ones you're using. But only integer keys (or keys that can be cleanly converted to integers) are actually treated as elements of an Array. This is why JSON isn't catching your properties, and it's also why your Arrays are all reporting their length as zero.

If you really need to use non-integer keys, you should be using plain Objects, not Arrays. This method has its own gotchas -for example, you need to be careful with for-in loops- but JSON will work the way you expect it to.

var hours = {
    "Mon" : {
        "11h30" : "15h00",
        "18h30" : "21h30"
    }, 
    "Tue" : {},
    "Wed" : {
        "11h30" : "15h00",
        "18h30" : "21h30"
    }, 
    "Thu" : {},
    "Fri" : {},
    "Sat" : {},
    "Sun" : {
        "11h30" : "15h00",
        "18h30" : "21h30"
    }, 
}
The Spooniest
  • 2,863
  • 14
  • 14
2

In javascript arrays have indexes that are numeric keys. JSON.stringify assumes that an array have only properties which are numbers.

You want to use an object, as what you have is not an array, but resembles a dictionary.

Here is an example I made: http://jsfiddle.net/developerwithacaffeineproblem/pmxt8bwf/2/

object = Object()
object["age"] = 1
object["cars"] = 2
object["girlfriends"] = 3

JSON.stringify(object)

Results in:
"{"age":1,"cars":2,"girlfriends":3}"

Afterwards when you parse the data if you want to iterate it you can use a piece of code similiar to this:

for (var key in yourobject) {
  if (yourobject.hasOwnProperty(key)) {
     console.log(key, yourobject[key]);
  }
}
-1

you can use

const newMap = JSON.parse('{}');
newMap[name] = value;

and stingfy newMap. The result is pars as Map<string, string>