I am biggener with JSON
I have the following in my JSON file (file-1) :
{
"Aps": [
{
"type": "opo",
"price_min": 7,
"price_max":10,
"app_time": 0,
"arguments": {
"prices": 15,
"apps_num": "112"
},
"attributes": {
"name":"user1",
"priority":"100"
}
}
}
How write python code that generates another JSON file that contain the same content of file-1 but duplicated 100 time in each time the name of user is different user2, user3 ... user100 and also it's priority.
I have tried the following but it is not working :
for lp in range(100):
with open("sample.json", "w") as outfile:
outfile.write(json_object)
but it is not working ..
the required output is as follow :
{
"Aps": [
{
"type": "opo",
"price_min": 7,
"price_max":10,
"app_time": 0,
"arguments": {
"prices": 15,
"apps_num": "112"
},
"attributes": {
"name":"user1",
"priority":"100"
}
},
{
"type": "opo",
"price_min": 7,
"price_max":10,
"app_time": 0,
"arguments": {
"prices": 15,
"apps_num": "112"
},
"attributes": {
"name":"user2",
"priority":"90"
}
},
{
"type": "opo",
"price_min": 7,
"price_max":10,
"app_time": 0,
"arguments": {
"prices": 15,
"apps_num": "112"
},
"attributes": {
"name":"user2",
"priority":"80"
}
},
..............
}
I made a little code here using json and copy module
json for reading and writing json files
copy because I had some trouble with reference variables see documentation for copy; if I changed 'temp' dict then it would affect all occurrences in 'file' dict
import json
import copy
repeats = 100
file = json.loads(open('file.json', 'r').read())
temp1 = json.loads(open('file.json', 'r').read())['Aps'][0]
for repeat in range(repeats):
temp = copy.deepcopy(temp1)
temp['attributes']['name'] = f"user{repeat + 2}"
temp['attributes']['priority'] = f"{repeat*10+100 - repeat*20}"
file['Aps'].append(temp)
temp1 = copy.deepcopy(temp)
json.dump(file, open('file1.json', 'w'), indent=4)
You should first convert your json file to a python object (dict):
import json
file = open('sample.json')
data = json.load(file)
file.close()
Now you can do stuff with your Aps list, like appending the first object 100 times to your list.
for dups in range(100):
data['Aps'].append(data['Aps'][0])
Then you save your dict to a json file again:
with open("sample.json", "w") as outputfile:
json.dump(data, outputfile)
Related
I'm trying to update exsisting JSON file when running my code by adding additional data (package_id). this is the exsisting json contents:
{
"1": {
"age": 10,
"name": [
"ramsi",
"jack",
"adem",
"sara",
],
"skills": []
}
}
and I want to insert a new package and should looks like this:
{"1": {
"age": 10,
"name": [
"ramsi",
"jack",
"adem",
"sara",
],
"skills": []
} "2": {
"age": 14,
"name": [
"maya",
"raji",
],
"skills": ["writing"]
}
}
Issue is when I add the new data it adds --> ({) so (one top-level value) is added twice which is not allowed by JSON standards
{"1": {
"age": 10,
"name": [
"ramsi",
"jack",
"adem",
"sara",
],
"skills": []
}} {"2": {
"age": 14,
"name": [
"maya",
"raji",
],
"skills": ["writing"]
}
}
and this is my code to add the new (package_id):
list1[package_id] = {"age": x, "name": y, "skills": z}
ss = json.dumps(list1, indent=2)
data = []
with open('file.json', 'r+') as f:
data = json.loads(f.read())
data1 = json.dumps(data, indent=2)
f.seek(0)
f.write(data1)
f.write(ss)
f.truncate()
I write to the file twice because if I didn't store existing contents and write it again then it will remove old data and keeps only package_id number 2
It doesn't work that way. You can't add to a JSON record by appending another JSON record. A JSON file always has exactly one object. You need to modify that object.
with open('file.json','r') as f:
data = json.loads(f.read())
data[package_id] = {'age':x, 'name':y, 'skills':z}
with open('file.json','w') as f:
f.write(json.dumps(data,indent=2))
Context: I have a list with the structure below. It can contain a variable number of items, in multiples of 3. I am trying to transform each set of 3 into a separate JSON document.
['SCAN1.txt', 'Lastmodified:20191125.121049', 'Filesize:7196', 'SCAN2.txt', 'Lastmodified:20191125.121017', 'Filesize:3949', 'SCAN3.txt', 'Lastmodified:20191125.121056', 'Filesize:2766']
Question: How can I convert the single list into a JSON document with the following form, while also allowing for variability in the number of files it can accomadate:
{
{
"File": {
"File_Name":"SCAN1.txt",
"Last_Modified":"20191125.121049",
"File_Size":"7196"
}
{
"File": {
"File_Name":"SCAN2.txt",
"Last_Modified":"20191125.121017",
"File_Size":"3949"
}
}
{
"File": {
"File_Name":"SCAN3.txt",
"Last_Modified":"20191125.121056",
"File_Size":"2766"
}
}
}
Using chunked from more-itertools,
from more_itertools import chunked
import json
example = ['SCAN1.txt', 'Lastmodified:20191125.121049', 'Filesize:7196', 'SCAN2.txt', 'Lastmodified:20191125.121017', 'Filesize:3949', 'SCAN3.txt', 'Lastmodified:20191125.121056', 'Filesize:2766']
def file_to_json(file):
return {"File": {"File_Name": file[0], "Last_Modified": file[1], "File_Size": file[2]}}
json.dumps([file_to_json(file) for file in list(chunked(example, 3))])
Output:
[{
"File": {
"File_Name": "SCAN1.txt",
"Last_Modified": "Lastmodified:20191125.121049",
"File_Size": "Filesize:7196"
}
}, {
"File": {
"File_Name": "SCAN2.txt",
"Last_Modified": "Lastmodified:20191125.121017",
"File_Size": "Filesize:3949"
}
}, {
"File": {
"File_Name": "SCAN3.txt",
"Last_Modified": "Lastmodified:20191125.121056",
"File_Size": "Filesize:2766"
}
}]
You could also change your result to have the filenames as keys instead, since they are unique:
{
"SCAN1.txt": {
"Filesize": 7196,
"Lastmodified": 20191125.121049
},
"SCAN2.txt": {
"Filesize": 3949,
"Lastmodified": 20191125.121017
},
"SCAN3.txt": {
"Filesize": 2766,
"Lastmodified": 20191125.121056
}
}
Which could be achieved like below(comments included):
from collections import defaultdict
from json import dumps
from ast import literal_eval
lst = [
"SCAN1.txt",
"Lastmodified:20191125.121049",
"Filesize:7196",
"SCAN2.txt",
"Lastmodified:20191125.121017",
"Filesize:3949",
"SCAN3.txt",
"Lastmodified:20191125.121056",
"Filesize:2766",
]
def group_file_documents(lst, prefix="SCAN"):
# Use defaultdict of dicts to represent final JSON structure
# Also can be serialized like normal dictionaries
result = defaultdict(dict)
current_file = None
for item in lst:
# Update current file name if starts with prefix
if item.startswith(prefix):
current_file = item
continue
# Ensure current file name is present
if current_file:
# Split key.values and strip whitespace, just in case
key, value = map(str.strip, item.split(":"))
# Convert to actual int/float value
result[current_file][key] = literal_eval(value)
return result
# Print serialized JSON file with sorted keys and indents of 4 spaces
print(dumps(group_file_documents(lst), sort_keys=True, indent=4))
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 which has some key-value pairs in Arrays. I need to update/replace the value for key id with a value stored in a variable called Var1
The problem is that when I run my python code, it adds the new key-value pair in outside the inner array instead of replacing:
PYTHON SCRIPT:
import json
import sys
var1=abcdefghi
with open('C:\\Projects\\scripts\\input.json', 'r+') as f:
json_data = json.load(f)
json_data['id'] = var1
f.seek(0)
f.write(json.dumps(json_data))
f.truncate()
INPUT JSON:
{
"channel": "AT",
"username": "Maintenance",
"attachments": [
{
"fallback":"[Urgent]:",
"pretext":"[Urgent]:",
"color":"#D04000",
"fields":[
{
"title":"SERVERS:",
"id":"popeye",
"short":false
}
]
}
]
}
OUTPUT:
{
"username": "Maintenance",
"attachments": [
{
"color": "#D04000",
"pretext": "[Urgent]:",
"fallback": "[Urgent]:",
"fields": [
{
"short": false,
"id": "popeye",
"title": "SERVERS:"
}
]
}
],
"channel": "AT",
"id": "abcdefghi"
}
Below will update the id inside fields :
json_data['attachments'][0]['fields'][0]['id'] = var1
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)