简体   繁体   中英

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.

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.

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.

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