Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store multiple values in single key in json

Tags:

json

arrays

I need to store many values in single key of json. e.g.

{   "number" : "1","2","3",   "alphabet" : "a", "b", "c" } 

Something like this. Any pointers?

like image 772
Gaurav Avatar asked Jun 13 '13 17:06

Gaurav


People also ask

Can JSON key have multiple values?

JSON array can store multiple values. It can store string, number, boolean or object in JSON array. In JSON array, values must be separated by comma.

Can JSON have multiple keys with same name?

There is no "error" if you use more than one key with the same name, but in JSON, the last key with the same name is the one that is going to be used. In your case, the key "name" would be better to contain an array as it's value, instead of having a number of keys "name".

Can JSON have spaces in keys?

Whitespace (Space, Horizontal tab, Line feed or New line or Carriage return) does not matter in JSON. It can also be minified with no affect to the data. Object literal names MUST be lowercase (ie – null, false, true etc).


2 Answers

Use arrays:

{     "number": ["1", "2", "3"],     "alphabet": ["a", "b", "c"] } 

You can the access the different values from their position in the array. Counting starts at left of array at 0. myJsonObject["number"][0] == 1 or myJsonObject["alphabet"][2] == 'c'

like image 150
Elliot Bonneville Avatar answered Nov 13 '22 20:11

Elliot Bonneville


{   "number" : ["1","2","3"],   "alphabet" : ["a", "b", "c"] } 
like image 26
marekful Avatar answered Nov 13 '22 20:11

marekful