Reputation: 17
I want to store data in a .json file as using python language-
{object:
{
name: "abcd",
id: "fwfwfwf"
}
{
name: "efgh",
id: "wderds"
}
..
.. and so on
}
{container:
{
name: "pros",
id: "zxcdsef"
}
{
name: "mnop",
id: "waqsred"
}
..
.. and so on
}
Again now I want to read particular member of object/container in the file using f.read() or similar methods.\
How can I parse this file using python and JSON ??
#Sir One more thing I want to ask. Suppose my data.json file is like -
{
"object": [
{
"name": "abcd",
"id": "fwfwfwf"
},
{
"name": "efgh",
"id": "wderds"
}
]
}
{
"container": [
{
"name": "pqrs",
"id": "fwfwfwf"
},
{
"name": "mnop",
"id": "wderds"
}
]
}
Now I want to add one more container in this file which will go under Containers. Can you please tell me how will I write new container in the file using f.write()
Upvotes: 0
Views: 120
Reputation: 4014
This is the syntax for dumping data into JSON prettily.
with open('abc.json', 'wb') as outfile:
json.dump(obj, outfile, indent = 4)
For loading from JSON file, use
with open('abc.json') as infile:
data = json.load(infile)
More info http://freepythontips.wordpress.com/2013/08/08/storing-and-loading-data-with-json/
Upvotes: 0
Reputation: 1232
first create valid json. You can validate your json using any link like
{
"object": [
{
"name": "abcd",
"id": "fwfwfwf"
},
{
"name": "efgh",
"id": "wderds"
}
]
}
Now python script
import json
with open('data.json') as data_file:
data = json.load(data_file)
And you can access data like:
data["objects"][0]["id"] # will return 'fwfwfwf'
data["objects"][1]["name"] #will return 'efgh'
Upvotes: 2
Reputation: 1300
use http://jsonlint.com/
to validate your json. In json files identifiers have double quotes. numbers int/float need not have.
In general a json file is a python dictionary in text format. You can use the json module to parse json files.
import json
myfile = open('yourfilename', 'r')
myjsondata_as_dict = json.load(myfile)
after this myjsondata_as_dict will have your json data as a dictionary, provided there were no errors in json format.
Upvotes: 0