0

got some problems when using following code:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json
import os
summarydatei = 'teste.json'

def validateJSONFile(jsonData):
    try:
        json.load(jsonData)
    except Exception:
        return False
    return True

data_dict = {
    "nachrichten": {
        "absender": "absender", 
        "inhalt": "inhalt", 
        "uhrzeit": "uhrzeit", 
        "geheim": "geheim"
    }
}

data = json.dumps(data_dict, indent=4, sort_keys=True)
#try:
if os.path.isfile(summarydatei):
    with open(summarydatei, "r") as json_file: 
        if validateJSONFile(json_file):
            print("is json")
            data_new = json.load(json_file)
            print(data_new)
            data = data + data_new
            print(data)
with open(summarydatei, "w+") as json_file: 
    json.dump(data, json_file, sort_keys=True, indent=4)
#except Exception:
#    pass

In first execution it creates a json file which is formatted right and its content can be loaded as a string with json.loads but not when I use it with file loading. I want to add new data to the existing json with each execution.

Following error is shown for me with python 3.7:

---------------------------------------------------------------------------
JSONDecodeError                           Traceback (most recent call last)
<ipython-input-67-46810757cce1> in <module>
      3         if validateJSONFile(json_file):
      4             print("is json")
----> 5             data_new = json.load(json_file)
      6             print(data_new)
      7             data = data + data_new

e:\Anaconda3\lib\json\__init__.py in load(fp, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
    294         cls=cls, object_hook=object_hook,
    295         parse_float=parse_float, parse_int=parse_int,
--> 296         parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
    297 
    298 

e:\Anaconda3\lib\json\__init__.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
    346             parse_int is None and parse_float is None and
    347             parse_constant is None and object_pairs_hook is None and not kw):
--> 348         return _default_decoder.decode(s)
    349     if cls is None:
    350         cls = JSONDecoder

e:\Anaconda3\lib\json\decoder.py in decode(self, s, _w)
    335 
    336         """
--> 337         obj, end = self.raw_decode(s, idx=_w(s, 0).end())
    338         end = _w(s, end).end()
    339         if end != len(s):

e:\Anaconda3\lib\json\decoder.py in raw_decode(self, s, idx)
    353             obj, end = self.scan_once(s, idx)
    354         except StopIteration as err:
--> 355             raise JSONDecodeError("Expecting value", s, err.value) from None
    356         return obj, end

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Any suggestions or advise?

--[Solution]-- Changed code to following:

data_dict = {
    "absender": "absender", 
    "inhalt": "inhalt", 
    "uhrzeit": "uhrzeit", 
    "geheim": "geheim"
}

temp = []
if not os.path.isfile(summarydatei) or os.stat(summarydatei).st_size == 0:
    temp.append(data_dict)
    with open(summarydatei, mode='w') as f:
        f.write(json.dumps(temp, indent=2))
else:
    with open(summarydatei) as feedsjson:
        feeds = json.load(feedsjson)

    feeds.append(data_dict)
    with open(summarydatei, mode='w') as f:
        f.write(json.dumps(feeds, indent=2))

Now it works like a charm. Thank you.

halfti
  • 1
  • 1
  • See [How to append data to a json file?](https://stackoverflow.com/questions/12994442/how-to-append-data-to-a-json-file/12994577#12994577) in regards to appending to a json file. – Trenton McKinney Jun 14 '20 at 19:35
  • 1
    Thank you, found this tread yesterday but used to find an alternative way. But now it's working. Changed my code in opening text. – halfti Jun 14 '20 at 20:26

0 Answers0