Questions
Questions

Reputation: 20895

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

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
        }
    }
}  

Upvotes: 15

Views: 28868

Answers (3)

Greg Hewgill
Greg Hewgill

Reputation: 993611

JSON requires the quotes. See http://json.org for the specifications.

In particular, the string production is:

string
    '"' characters '"'

Upvotes: 12

DaveL17
DaveL17

Reputation: 2013

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)

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630509

The first is valid, if you're unaware you can validate your JSON output online pretty easily here: http://www.jsonlint.com/

Upvotes: 22

Related Questions