1

I need to write the outputs to a json file in python. I have tried some of the answers here to write to a json file but for some reason I am not finding the correct format I need the data written to a json file.

What I am looking at is:

{
  {
  "Region": "BD",
  "name": "bdfe",
  "tyl": "cya",
  "ice": "messi",
  "fed": "bet",
   },
   {
  "Region": "Toron",
  "name": "Cana",
  "tyl": "cyab",
  "ice": "feed",
  "fed": "not",
   },
  ...

}

How can I write in this format in python?

Thank you

Shad
  • 15
  • 4

2 Answers2

1

Firstly, your 'json' is wrong. I'm assuming the outer curly brackets should be square brackets and you thus trying to save a list. Sets are not part of the json format. Assuming this answer is not what you want because the output is not formatted, you can use the documentation to format the file as you need it. For example:

Python 3.7.0 (default, Nov 21 2018, 10:19:24) 
Type 'copyright', 'credits' or 'license' for more information
IPython 7.1.1 -- An enhanced Interactive Python. Type '?' for help.

In [1]: import json                                                                                            

In [2]: obj = [{ 
   ...:   "Region": "BD", 
   ...:   "name": "bdfe", 
   ...:   "tyl": "cya", 
   ...:   "ice": "messi", 
   ...:   "fed": "bet", 
   ...:    }, 
   ...:    { 
   ...:   "Region": "Toron", 
   ...:   "name": "Cana", 
   ...:   "tyl": "cyab", 
   ...:   "ice": "feed", 
   ...:   "fed": "not", 
   ...:    }]                                                                                                  

In [3]: with open('data.json', 'w') as outfile: 
   ...:     json.dump(obj, outfile, indent=4) 
   ...:                                                                                                        

In [4]: !cat data.json                                                                                         
[
    {
        "Region": "BD",
        "name": "bdfe",
        "tyl": "cya",
        "ice": "messi",
        "fed": "bet"
    },
    {
        "Region": "Toron",
        "name": "Cana",
        "tyl": "cyab",
        "ice": "feed",
        "fed": "not"
    }
]
Paul Whipp
  • 16,028
  • 4
  • 42
  • 54
0

Replicating that code in python is very simple. All you have to do is convert that to a dictionary. Here is the converted output:

import json


mydict = [{
"Region": "BD",
"name": "bdfe",
"tyl": "cya",
"ice": "messi",
"fed": "bet",
 },
 {
"Region": "Toron",
"name": "Cana",
"tyl": "cyab",
"ice": "feed",
"fed": "not",
 }]

with open('data.json', 'w') as out: 
    json.dump(mydict, out, indent = 2)

xilpex
  • 3,097
  • 2
  • 14
  • 45