Skip to content Skip to sidebar Skip to footer

Python - Updating Json Objects In A File

I have a (valid) JSON file contaning JSON objects, each object taking up one file line. These JSON objects map to Python dicts, and are in ascending order by numerical IDs. I am w

Solution 1:

You cannot do what you want, because you can only surgically replace fixed length records in a file. You cannot replace the line with something that is longer or shorter, as files don't store data as separate lines.

In addition, your code doesn't take into account that on some platforms (like on Windows) lines in text files are separated by two characters, representable in Python as \r\n, but these line endings are translated for you to the single character \n. Your line length calculation doesn't take that into account.

You instead have to rewrite everything following that line. You'd be better of using a database; sqlite3 comes bundled with Python, take a look at that.

Solution 2:

defupdate_JSON_file( self, file_path, obj_IDs, props ):
    decoder = json.JSONDecoder()
    with io.open( file_path, 'r+', encoding='utf=8' ) as files:
        IDs_iter = iter( obj_IDs )
        fl = files.read().splitlines(True)
        ID = IDs_iter.next()
        for i,line inenumerate(fl):
            # ID = IDs_iter.next()# I think the 'ID' should be initialized out of the loop# and iterated only if the condition is trueifstr(ID) in line:
                JSON_obj = decoder.raw_decode(line)[0]
                for key in props.keys():
                    JSON_obj[key] = props[key] 
                JSON_obj = json.dumps( JSON_obj, ensure_ascii=False )
                if'},\n'in line: JSON_obj += ',\n'
                JSON_obj = unicode( JSON_obj )
                fl[i] = JSON_obj
                try:
                    ID = IDs_iter.next()
                except StopIteration:
                    break
        files.seek(0)
        files.write(''.join(fl))
        returnTrue

Post a Comment for "Python - Updating Json Objects In A File"