Nick Miller
Nick Miller

Reputation: 29

Python - Remove Single Quotes From List Items When Adding To Dictionary

I have tried all the recommendations on similar posts, but have had no luck. I have a list of items that I'm using to create values for a list of dictionaries. That list ultimately becomes a JSON object, so I can't have the single quotes around each list item that I add to it.

metrics = ["test_met_1","test_met_2","test_met_3","test_met_4","test_met_5"]
data = {
    "reportDescription":{
        "reportSuiteID":"some_suite",
        "dateFrom":"yesterday",
        "dateTo":"today",
        "dateGranularity": "day",
        "metrics":[]
        }
    }

if len(metrics) > 0:
    for metric in metrics:
    new_met = "{\"id\""+":"+"\""+metric+"\"}"
    data["reportDescription"]["metrics"].append(new_met)

if len(elements) > 0:
    for element in elements:
        new_elm = "{\"id\""+":"+"\""+element+"\",\"top\""+":"+"\"50000\""+"}"
    data["reportDescription"]["elements"].append(new_elm)

log_file = open('test.JSON','a')
log_file.write('\n\n'+str(datetime.now())+'\n'+str(data))
log_file.close()

My Results:

{'reportDescription':'dateGranularity': 'day', 'dateTo': 'today', 'dateFrom': 'yesterday', 'metrics': ['{"id":"test_met_1"}', '{"id":"test_met_2"}', '{"id":"test_met_3"}', '{"id":"test_met_4"}', '{"id":"test_met_5"}'], 'reportSuiteID': 'some_suite'}

What I actually need:

{"reportDescription":"dateGranularity": "day", "dateTo": "today", "dateFrom": "yesterday", "metrics": [{"id":"test_met_1"}, {"id":"test_met_2"}, {"id":"test_met_3"}, {"id":"test_met_4"}, {"id":"test_met_5"}], "reportSuiteID": "some_suite"}

Any ideas on how to remove those single quotes around each list item? I've tried a couple variations of join() and/or replace(). No luck though.

Upvotes: 0

Views: 1853

Answers (2)

tobias_k
tobias_k

Reputation: 82899

If you want to create a JSON string (or file), use the json module.

>>> data["reportDescription"]["metrics"] = [{"id": m} for m in metrics]
>>> json.dumps(data)
'{"reportDescription": {"metrics": [{"id": "test_met_1"}, {"id": "test_met_2"}, {"id": "test_met_3"}, {"id": "test_met_4"}, {"id": "test_met_5"}], "dateFrom": "yesterday", "dateGranularity": "day", "reportSuiteID": "some_suite", "dateTo": "today"}}'

To write to file directly, use json.dump(data, log_file). The json module will take care of properly escaping strings and using the correct JSON quotes etc.

Upvotes: 1

be_good_do_good
be_good_do_good

Reputation: 4441

Once you have resultant dictionary, convert it to json object using json.dumps(yourdict)

Don't forget import json

Make sure your dictionary is a good.

Upvotes: 0

Related Questions