What is the correct format in JSON, should I quote names also?
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)
JSON requires the quotes. See http://json.org for the specifications.
In particular, the string production is:
string
'"' characters '"'
The first is valid, if you're unaware you can validate your JSON output online pretty easily here: http://www.jsonlint.com/