-5

i have two list, one is column names and another one is data type and i would like to form a json.

sample code:

columnNameList = ["name", "age"]
dataTypeList = ["string",  "int"]
colDataList = [{"colName": k, "dataType": v} for k, v in zip(columnNameList, dataTypeList)]
colDataDict = {"schema": colDataList}
print(colDataDict)

The above code gives me the below output, but everything is enclosed with single quotes, why is that? also is this the best way of doing it?

sample output:

{  

       'schema':[  
          {  
             'colName':'name',
             'dataType':'string'
          },
          {  
             'colName':'age',
             'dataType':'int'
          }
       ]
    }
Shankar
  • 8,529
  • 26
  • 90
  • 159
  • Because in python both single and double quotes represent strings –  May 15 '18 at 15:50
  • 1
    You are creating a dictionary in there, not a json object. This might be helpful https://stackoverflow.com/questions/26745519/converting-dictionary-to-json-in-python – yash May 15 '18 at 15:51
  • @SembeiNorimaki: but this is not a valid json, json should come with double quotes. – Shankar May 15 '18 at 15:51
  • well you are not creating json in the first place @Shankar, you have to use `json.dumps(colDataDict)` to get the json object that you need – yash May 15 '18 at 15:53

1 Answers1

2

Everything is enclosed within single quotes

That's because Python is trying to display Python strings, which may be enclosed in single or in double quotes. If you want JSON formatted output you have to format it as JSON:

import json
print(json.dumps(colDataDict))
user234461
  • 1,133
  • 12
  • 29