简体   繁体   中英

Invalid Json using json.dump in python3

My generated json output is showing that it's not a valid Json while checking with jslint. Getting error EOF.

Here am using if len(data) != 0: for not inserting [] in the final output.json file (working but don't know any other way to avoid inserting [] to file)

with open('output.json', 'a') as jsonFile:
        print(data)
        if len(data) != 0:
            json.dump(data, jsonFile, indent=2)

My input data is coming one by one from another function generated from inside for loop.

Sample "data" coming from another function using loop :

print(data)

[{'product': 'food'}, {'price': '$100'}]
[{'product': 'clothing'}, {'price': '$40'}]

...

Can I append these data and make a json file under "Store". What should be the the proper practice. Please suggest.

Sample output generated from output.json file :

[
  {
    "product": "food"
  },
  {
    "price": "$100"
  }
][
  {
    "product": "clothing"
  },
  {
    "price": "$40"
  }
]

Try jsonlines package, you would need to install it using pip install jsonlines .

jsonlines does not contain the comma(,) at the end of line. So you can read and write exact structure the way you have anod you would not need to do any additional merge or formatting.

import jsonlines
with jsonlines.open('output.json') as reader:
    for obj in reader:
     // Do something with obj

Similarly, you can do the dump but by write method of this module.

with jsonlines.open('output.json', mode='w') as writer:
    writer.write(...)

output.jsonl would look like this

[{'product': 'food'}, {'price': '$100'}]
[{'product': 'clothing'}, {'price': '$40'}]

Yes, You can always club them all together and link it to a key named Store which would make sense as they are all the products in the store.

But I think the below format would be much better as each product in the store have a defined product name along with the price of that product

{
   "Store":[
      {
         "product":"food",
         "price":"$100"
      },
      {
         "product":"clothing",
         "price":"$40"
      }
   ]
}

If you do this way you need not have to insert each and every key,value pair to the json but instead if you can simply insert the entire product name and price to a single object and keep appending it to the store list

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM