I have constructed a json object from a data stream where each user will have a json object.
{
"entities": {
"description": {
"urls": []
}
},
"utc_offset": -10800,
"id"
"name": "Tom",
"hit_count": 7931,
"private": false,
"active_last_month": false,
"location": "",
"contacted": false,
"lang": "en",
}
Objective: I want to construct a json file where each json object become a line in a file with the indentation. And when it comes to reading back the JSON file it can be read using with open:
for example: Following File
[
{
"entities": {
"description": {
"urls": []
}
},
"utc_offset": -10800,
"id"
"name": "Tom",
"hit_count": 7931,
"private": false,
"active_last_month": false,
"location": "",
"contacted": false,
"lang": "en",
}
,
{
"entities": {
"description": {
"urls": []
}
},
"utc_offset": -10500,
"id"
"name": "Mary",
"hit_count": 554,
"private": false,
"active_last_month": false,
"location": "",
"contacted": false,
"lang": "en",
}
]
Above file can easily read by:
with open(pathToFile) as json_file:
json_data = json.load(json_file)
for key in json_data:
print key["id"]
But at the moment here is how I am writing constructing the json file:
with open(root + filename + '.txt', 'w+') as json_file:
# convert from Python dict-like structure to JSON format
jsoned_data = json.dumps(data)
json_file.write(jsoned_data)
json_file.write('\n')
This gives me
{
indented json data
}
{
indented json data
}
PS: notice brackets []
are not there along with ,
When you try to read this same code structure as
with open(pathToFile) as json_file:
json_data = json.load(json_file)
for key in json_data:
print key["id"]
you end up getting errors:
ValueError: Extra data: line 101 column 1 - line 1889 column 1