0

Objective: Get all row in CSV file (minimum 1 row & more), add fix string & use the variable in JSON array.

Sorry, if the question is not related. I'm not sure what the correct question to be asked.

I want the "entryList" format to be like below, for successfully post the JSON object.

But, none of below approach works.

"entryList": [
 {"entry": ["value_from","csv",""]},
 {"entry": ["value_from","csv",""]},
 {"entry": ["value_from","csv",""]}
]

Dumps JSON (full format):

x={
"act.addEntries": {
"act.authToken": "test123",
"act.resourceId": "asdasda=123asd1",
"act.entryList": {
   "columns": [
     "domainName","threatInfo","riskScore"
   ],
   "entryList": [
     VARIABLE
   ]
  }
 }
}

"""
Sample CSV file
domainName,threatInfo,riskScore
xxx.xxx.com,Test1,
yyy.yyy.com,Test2,
zzz.zzz.com,Test3,
"""

# CSV to List
domainList=[]
with open('Desktop/domainMatches.csv', 'r') as file:
reader = csv.reader(file)

col = next(reader)

Approach 1 - String Formatting

Problem: JSON dumps only show 1 entryList value. I couldn't get the correct way to escape {}, hence it lead to undesired JSON Object

for data in reader:
    domainList.append(data)
    line= '{{"entry": {}}}'.format(data)
    print(line)

**OUTPUT:**
{"entry": ['xxx.xxx.com', 'Test1', '']}
{"entry": ['yyy.yyy.com', 'Test2', '']}
{"entry": ['zzz.zzz.com', 'Test3', '']}
...
...
"entryList": [
  {{{}}}.format(line)
 ]

**OUTPUT - JSON Dumps:**
{
  "act.addEntries": {
    "act.authToken": "test123",
    "act.resourceId": "asdasda=123asd1",
    "act.entryList": {
      "columns": [
        "domainName",
        "threatInfo",
        "riskScore"
      ],
      "entryList": [
        "{{\"entry\": ['zzz.zzz.com', 'Test3', '']}}"
      ]
    }
  }
}

Aprroach 2 - + Concatenation

Too many problem here as well. Advice if needed

line = ""
for value in reader:
    line+="{"
    line+=""" "entry": """
    line+=str(value)
    line+="},\n"

**OUTPUT:**
{"entry": ['xxx.xxx.com', 'Test1', '']},
{"entry": ['yyy.yyy.com', 'Test2', '']},
{"entry": ['zzz.zzz.com', 'Test3', '']},
...
...
"entryList": [
 """+line+"""
 ]

0 Answers0