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()
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'
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.
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/
Related
"attributes": [
{
"trait_type": "Vintage",
"value": 2019
},
{
"trait_type": "Volume (ml)",
"value": 750
}
]
I want to change the 2019 and the 750 to a string (by including "") for multiple values over 150+ JSONs using python
I am not a dev and do not use Python, but I have this so far:
import json
for i in range(1, 147):
with open(f'{i}.json', 'r+', encoding='utf8') as f:
data = json.load(f)
You can make a function that takes a JSON file name and replaces these specific values you're looking for:
def change_values_to_string(json_filename):
with open(f'{json_filename}.json', 'r') as json_fp:
json_to_dict = json.loads(json_fp.read())
for sub_dict in json_to_dict["attributes"]:
sub_dict["value"] = str(sub_dict["value"])
with open(f'{json_filename}.json', 'w') as json_fp:
json_fp.write(json.dumps(json_to_dict))
for _ in range(1, 147):
change_values_to_string(_)
Input:
test.json
{
"attributes": [
{
"trait_type": "Vintage",
"value": 2019
},
{
"trait_type": "Volume (ml)",
"value": 750
}
]
}
Calling the function with the correct file name: change_values_to_string("test")
Outputs:
{
"attributes": [
{
"trait_type": "Vintage",
"value": "2019"
},
{
"trait_type": "Volume (ml)",
"value": "750"
}
]
}
Explanations:
Open the json file in read mode - and loading it into a dictionary python type.
Iterate over the attributes key which contains a lot of dictionaries if I get it right.
Replace each value key to a string
Dump the dictionary into the same file overriding it.
I am looking for a way to convert a JSONL file to JSON.
I have written a python program but at some point it's just getting to slow because the JSON file gets to big. And with every loop I checked if the keys are in there…
Maybe some of you has an idea on how to write a program that does the following:
The JSONL file is from a Firebase export, which looks like this:
{"__path__":"cars/89dHLbXAOooudSNHv6Jt","__exportPath__":"","__id__":"89dHLbXAOooudSNHv6Jt","brandId":"Fp5Kwr7NXNRPxY7Yx3QK","name":"Testuser", "email": "test.user#email.com", "settings":{"test1":true,"test2":true}}
The document can also have subcollections:
{"__path__":"cars/89dHLbXAOooudSNHv6Jt/subcollection/dwadwadawdwaddwa","__exportPath__":"","__id__":"dwadwadawdwaddwa","modelId":"d54321242","name":"testcar", "motor": "example f1"
this needs to be converted into this:
{
"cars": {
"89dHLbXAOooudSNHv6Jt": {
"brandId": "Fp5Kwr7NXNRPxY7Yx3QK",
"name": "Testcar",
"email": "test.user#email.com",
"settings": {
"test1": true,
"test2": true
},
"subcollection": {
"dwadwadawdwaddwa": {
"modelId": "d54321242",
"name": "testcar",
"motor": "example f1"
}
}
}
}
}
I have a json file saved in local server, such as:
{
"user": "user1",
"id": "21779"
}
and I want to write another dict into this json file, I need new content like this:
{
{
"user": "user1",
"id": "21779"
},
{
"user": "user2",
"id": "21780"
}
}
Or:
[
{
"user": "user1",
"id": "21779"
},
{
"user": "user2",
"id": "21780"
}
]
I try to use json.dump() to add the new element, but is displayed as:
{
"user": "user1",
"id": "21779"
}
{
"user": "user2",
"id": "21780"
}
It is not a valid json file.
How can I do use json.dump, json.load, or other methods?
Thanks for help me!
You have to read your JSON file and then convert it to list instead of dict. Then you just need to append to that list and overwrite your JSON file.
import json
data = json.load(open('data.json'))
# convert data to list if not
if type(data) is dict:
data = [data]
# append new item to data lit
data.append({
"user": "user2",
"id": "21780"
})
# write list to file
with open('data.json', 'w') as outfile:
json.dump(data, outfile)
You can do with the list not with the dict , try the below one solution if its help
import json
def appendList():
with open("test.json", mode='r', encoding='utf-8') as f:
feeds = json.load(f)
print(feeds)
with open("test.json", mode='w', encoding='utf-8') as feedsjson:
entry = { "user": "user3","id": "21574"}
feeds.append(entry)
print(json.dump(feeds, feedsjson))
I have a json file like as follows:
{
"category": {
"gender": {
"male": "A",
"female": "B"
},
"age": {
"young": 25
},
"dob": {
"dob_list": [
"crap"
]
}
},
"sample": {
"game1": {
"title": "<arg>",
"player": "john",
},
"game2": {
"title": "<arg>",
"game_location": "C:/game/<arg>/crap.exe",
"game_root": "C:/games/"
}
}
}
So i want to have some runtime arguments against "arg" in above json file passed from some python script or bat file. So can anyone suggest me how can i acheive that and which option is better to pass values a python script or bat file?
you can use json.load() on the file and then manipulate the contents of the file using dict comprehension
with open("file.json",'r') as f:
mydict = json.load(f)
mydict['sample']['game1']['title'] = yourValue
with open('file.json','w') as f:
f.write(str(mydict))
I've been looking around the web and I cannot find a way on adding new JSON data to array.
Example: I would like to add player_two, player_three through python.
{
"players": {
"player_one": {
"name": "Bob",
"age": "0",
"email": "bob#example.com"
}
}
}
How can I achieve doing this through python?
What I've tried:
with open("/var/www/html/api/toons/details.json", 'w') as outfile:
json.dump(avatarDetails, outfile)
Here is a simple example, read the file as a dict, update the dict, then use json.dumps() to get the json data:
import json
# open your jsonfile in read mode
with open('jsonfile') as f:
# read the data as a dict use json.load()
jsondata = json.load(f)
# add a new item into the dict
jsondata['players']['player_two'] = {'email': 'kevin#example.com', 'name': 'Kevin', 'age': '0'}
# open that file in write mode
with open('jsonfile', 'w') as f:
# write the data into that file
json.dump(jsondata, f, indent=4, sort_keys=True)
Now the file looks like:
{
"players": {
"player_one": {
"age": "0",
"email": "bob#example.com",
"name": "Bob"
},
"player_two": {
"age": "0",
"email": "kevin#example.com",
"name": "Kevin"
}
}
}
Assuming that your file contains this JSON:
{
"players": {
"player_one": {
"name": "Bob",
"age": "0",
"email": "bob#example.com"
}
}
}
You can parse the data into a Python dictionary using json.load():
with open('/var/www/html/api/toons/details.json') as f:
data = json.load(f)
Add your new players:
data['players']['player_two'] = dict(name='Bobbie', age=100, email='b#blah.com')
data['players']['player_three'] = dict(name='Robert', age=22, email='robert#blah.com')
Then save it back to a file:
with open('/var/www/html/api/toons/details.json', 'w') as f:
json.dump(data, f)