What is the correct format in JSON, should I quote names also?

Viewed 28273

I am writing a JSON file, but I am not sure about which of the following formats is the correct one?

Quoting variable names and all string values

{
    "class": {
        "number": 2,
        "student": {
            "name": "Tom",
            "age": 1
        },
        "student": {
            "name": "May",
            "age": 2
        }
    }
}

or

Quoting only string values

{
    class: {
        number: 2,
        student: {
            name: "Tom",
            age: 1
        },
        student: 
        {
            name: "May",
            age: 2
        }
    }
}  
3 Answers

Old question, but the OP's JSON (first construction) may have the proper syntax, but it's going to cause trouble because it repeats the key student.

import simplejson

data = '''{
    "class": {
        "number": 2,
        "student": {
            "name": "Tom",
            "age": 1
        },
        "student": {
            "name": "May",
            "age": 2
        }
    }
}'''

data_in = simplejson.loads(data)
print(data_in)

Yields: {'class': {'number': 2, 'student': {'age': 2, 'name': 'May'}}}

Where unique keys student_1 and student_2:

import simplejson

data = '''{
    "class": {
        "number": 2,
        "student_1": {
            "name": "Tom",
            "age": 1
        },
        "student_2": {
            "name": "May",
            "age": 2
        }
    }
}'''

data_in = simplejson.loads(data)
print(data_in)

Yields: {'class': {'student_1': {'age': 1, 'name': 'Tom'}, 'number': 2, 'student_2': {'age': 2, 'name': 'May'}}}

UPDATE:
Agree with @Tomas Hesse that an array is better form. It would look like this:

import simplejson

data = '''{
    "class": {
        "number": 2,
        "students" : [
            { "name" : "Tom", "age" : 1 }, 
            { "name" : "May", "age" : 2 }
        ]
    }
}'''

data_in = simplejson.loads(data)
print(data_in)
Related