I am using python to delete and update a JSON file generated from the data provided by user, so that only few items should be stored in the database. I want to delete a particular object from the JSON file.
My JSON file is:
[
{
"ename": "mark",
"url": "Lennon.com"
},
{
"ename": "egg",
"url": "Lennon.com"
}
]
I want to delete the JSON object with ename mark.
As I am new to python I tried to delete it by converting objects into dict but it is not working. Is there any other way to do it?
i tried this one:
index=0
while index < len(data):
next=index+1
if(data[index]['ename']==data[next]['ename']):
print "match found at"
print "line %d and %d" %(next,next+1)
del data[next]
index +=1
Here's a complete example that loads the JSON file, removes the target object, and then outputs the updated JSON object to file.
#!/usr/bin/python
# Load the JSON module and use it to load your JSON file.
# I'm assuming that the JSON file contains a list of objects.
import json
obj = json.load(open("file.json"))
# Iterate through the objects in the JSON and pop (remove)
# the obj once we find it.
for i in xrange(len(obj)):
if obj[i]["ename"] == "mark":
obj.pop(i)
break
# Output the updated file with pretty JSON
open("updated-file.json", "w").write(
json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))
)
The main point is that we find the object by iterating through the objects in the loaded list, and then pop the object off the list once we find it. If you need to remove more than one object in the list, then you should store the indices of the objects you want to remove, and then remove them all at once after you've reached the end of the for loop (you don't want to modify the list while you iterate through it).
The proper way to json is to deserialize it, modify the created objects, and then, if needed, serialize them back to json.
To do so, use the json module. In short, use <deserialized object> = json.loads(<some json string>) for reading json and <json output> = json.dumps(<your object>) to create json strings.
In your example this would be:
import json
o = json.loads("""[
{
"ename": "mark",
"url": "Lennon.com"
},
{
"ename": "egg",
"url": "Lennon.com"
}
]""")
# kick out the unwanted item from the list
o = filter(lambda x: x['ename']!="mark", o)
output_string = json.dumps(o)
Your json file contains in a list of objects, which are dictionaries in Python. Just replace the list with a new one that doesn't have the object in it:
import json
with open('testdata.json', 'rb') as fp:
jsondata = json.load(fp)
jsondata = [obj for obj in jsondata if obj['ename'] != 'mark']
print(json.dumps(jsondata, indent=4))
You need to use the json module. I'm assuming python2. Try this:
import json
json_data = json.loads('<json_string>')
for i in xrange(len(json_data)):
if(json_data[i]["id"] == "mark"):
del json_data[i]
break
You have a list there with two items, which happen to be dictionaries. To remove the first, you can use list.remove(item) or list.pop(0) or del list[0].
http://docs.python.org/2/tutorial/datastructures.html#more-on-lists
Related
Is there anyway i can find the position of object by its key in Json file. I tried with the collection module but seems not to work with data from the json file even though its dictionary
reda.json file
[{"carl": "33"}, {"break": "55"}, {"user": "heake"}, ]
import json
import collections
json_data = json.load(open('reda.json'))
if type(json_data) is dict:
json_data = [json_data]
d = collections.OrderedDict((json_data))
h = tuple(d.keys()).index('break')
print(h)
Also tried this
j = 'break'
for i in json_data:
if j in i:
print(j.index('break'))
Result is 0
``
You can use enumerate to generate indices for a sequence:
json_data = [{"carl": "33"}, {"break": "55"}, {"user": "heake"}]
key = 'break'
for index, record in enumerate(json_data):
if key in record:
print(index)
This outputs: 1
You don't require collections for this. Simply use list comprehension to generate a list and then get the index.
Here's my code:
import json
json_data = json.load(open('reda.json'))
json_key_index = [key for key in json_data]
print(json_key_index.index("break"))
Also, looking at your reda.json the format doesn't seem pretty well-versed. I recommend changing the reda.json to:
{
"carl": "33",
"break": "55",
"user": "heake"
}
I've been trying to get a more readable output from a JSON list. I have not yet been successful. I hard-coded some data to see if I can get it as I want. This is what I did:
import json
jsonData = {
"person": {"FirstName": "Kwin", "LastName": "Harley", "Age": 25},
"DoB": {"DateOfBirth": "19/12/1996", "Birthplace": "Belgium"},
"insurer":{"id":"12345","contractNumber":"98765432",
"valid_from":"2020-10-01T00:00:00.000Z","valid_until":"2021-01-30T00:00:00.000Z",
"representativeID":"135792468",
"representativeEmail":"sample#test.com"}
}
jsonString = json.dumps(jsonData, sort_keys=False, indent=4)
print(jsonString)
Output 1
As you can see, the data is structured nicely.
Now, when I use my main code, the output looks like this:
Output 2
It just returns the data in 1 row :(
Is there a way to fix that? This is the code I have for that:
qrType = qr.type
qrData = json.dumps(qr.data.decode('utf-8'),sort_keys=True)
# print the QR type and data to the terminal
print("[INFORMATION] Found {} barcode:\n{}".format(qrType, qrData))
I don't think you're passing a dict to json.dumps() at all. qr.data is clearly a string, as you .decode() it. Presumably it's a json string, so you want to do something like this:
formatted_data = json.dumps(json.load(qr.data.decode()), indent=2)
print(formatted_data)
Currently I am exporting a database from firebase into a JSON but it is coming out in as an array.
[{"ConnectionTime": 19.23262298107147, "objectId": "01331oxpVT", "FirmwareRevision": "201504270003 Img-B", "DeviceID": "EDF02C74-6518-489E-8751-25C58F8C830D", "PeripheralType": 4, "updatedAt": "2015-10-09T04:01:39.569Z", "Model": "Bean", "HardwareRevision": "E", "Serial": "Serial Number", "createdAt": "2015-10-09T04:01:39.569Z", "Manufacturer": "Punch Through Design"}, {"ConnectionTime": 0.3193170428276062, "objectId": "018Mv1g6I8", "DeviceID": "42635033-DF3A-4109-A633-C3AB829BE114", "PeripheralType": 2, "updatedAt": "2015-12-08T04:20:41.950Z", "createdAt": "2015-12-08T04:20:41.950Z"}]
And then I get this error - Start of array encountered without start of object.'}]
How can I change this to not be an Array and just a list of data. I also need a line break between each set of data but Im assuming once I get the data out of the array the code I currently have will do that. My code is below. Thanks for the help!
firebase = firebase.FirebaseApplication('https://dataworks-356fa.firebaseio.com/')
result = firebase.get('/connection_info_parse', None)
# id_keys = map(str, result.keys()) #filter out ID names
with open("firetobqrestore1.json", "w") as outfile:
# for id in id_keys:
json.dump(result, outfile, indent=None)
outfile.write("\n")
It sounds like something in your workflow wants newline delimited JSON, although you haven't made it explicitly clear what is giving you this error.
With that caveat, I think this is what you are looking for:
import json
with open("firetobqrestore1.json", "w") as outfile:
for line in result:
json.dump(line, outfile, indent=None)
outfile.write("\n")
This will write individual json objects to each line.
This also assumes that result is an actual python object rather than a JSON string. If it's a string you will need to parse it first with something like:
result = json.loads(result)
If the elements of the list are not parsed ( they are strings), then loop through the list and convert each element to a json using json.loads(). Then, you can use json.dumps()
In case the elements of the list are already parsed,then just loop through the list and use json.dumps().
I have a json file with multiple json dictionaries:
the format is as following
{"x":"1", "y":"2", "z": "3"}{"x": "2","y":"3", "z":"4"}{"x":"3", "y":"4", "z":"5"}
How can I convert this to one json dictionary format as following:
{"items":[{"x":"1", "y":"2", "z": "3"},{"x": "2","y":"3", "z":"4"},{"x":"3", "y":"4", "z":"5"}]}
Already mostly answered here: Importing wrongly concatenated JSONs in python
That shows you how to pick up each JSON element from a concatenated list of them (which is not valid JSON) using json.JSONDecoder method raw_decode(). The rest is a simple matter of concatenating strings '{"items":[', element1, ",", element2, ... "]" or alternatively, accumulating them as a list, wrapping that with a one-item dict and if required, dumping that json as a string with json.dumps
OK expanding on that
import json
d = json.JSONDecoder()
# get your concatenated json into x, for example maybe
x = open('myfile.json','r').read()
jlist=[]
while True:
try:
j,n = d.raw_decode(x)
jlist.append(j)
except ValueError:
break
x=x[n:]
# my original thought was
result = '{"items":[' +
','.join( [ str(s) for s in jlist] ) +
']'
# but this is neater
result = json.dumps( { "items":jlist })
# and of course if you want it for programmatic use, just
result_as_json = dict( items=jlist )
I am trying to output the following JSON from my python (2.7) script:
[
{
"id": "1002-00001",
"name": "Name 1"
},
{
"id": "1002-00002",
"display": "Name 2"
},
]
What data structure in Python will output this when using json.dumps?
The outermost item is a python list, but what should be the type of items inside the list? It looks like a dictionary with no keys?
Hopefully this clarifies the notes in comments that are not clear for you. It's achieved by appending (in this case small) dictionaries into a list.
import json
#Added an extra entry with an integer type. Doesn't have to be string.
full_list = [['1002-00001', 'Name 1'],
['1002-00002', 'Name 2'],
['1002-00003', 2]]
output_list = []
for item in full_list:
sub_dict = {}
sub_dict['id'] = item[0] # key-value pair defined
sub_dict['name'] = item[1]
output_list.append(sub_dict) # Just put the mini dictionary into a list
# See Python data structure
print output_list
# Specifically using json.dumps as requested in question.
# Automatically adds double quotes to strings for json formatting in printed
# output but keeps ints (unquoted)
json_object = json.dumps(output_list)
print json_object
# Writing to a file
with open('SO_jsonout.json', 'w') as outfile:
json.dump(output_list, outfile)
# What I think you are confused about with the "keys" is achieved with an
# outer dictionary (but isn't necessary to make a valid data structure, just
# one that you might be more used to seeing)
outer_dict = {}
outer_dict['so_called_missing_key'] = output_list
print outer_dict