Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
207 views
in Technique[技术] by (71.8m points)

Pass Variable into String vale which is JSON in Python

I need to pass one variable as date variable in place of Sting value I need to pass date in place of 2020-12-31

My String Values Looks like

from datetime import datetime, timedelta

date =(datetime.now() - timedelta(2)).strftime('%Y-%m-%d')

TableMappings="""{
    "rules": [
        {
            "rule-type": "selection",
            "rule-id": "1",
            "rule-action": "include",
            "object-locator": {
                "schema-name": "SCHEMA",
                "table-name": "AUDIT_TABLE"
            },
            "rule-name": "1",
            "filters": [
                {
                    "filter-type": "source",
                    "column-name": "UTC_DATE_TIME",
                    "filter-conditions": [
                        {
                            "filter-operator": "gte",
                            "value": "2020-12-31"
                        }
                    ]
                }
            ]
        }
    ]
}"""

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You don't necessarily need to operate with string representation of JSON and trying to template it, you can work with built-in dict data type.

import json
from datetime import datetime, timedelta

date =(datetime.now() - timedelta(2)).strftime('%Y-%m-%d')

dict_mapping = {
    "rules": [
        {
            "rule-type": "selection",
            "rule-id": "1",
            "rule-action": "include",
            "object-locator": {
                "schema-name": "SCHEMA",
                "table-name": "AUDIT_TABLE"
            },
            "rule-name": "1",
            "filters": [
                {
                    "filter-type": "source",
                    "column-name": "UTC_DATE_TIME",
                    "filter-conditions": [
                        {
                            "filter-operator": "gte",
                            "value": date
                        }
                    ]
                }
            ]
        }
    ]
}

str_mapping = json.dumps(dict_mapping)

Trying to format nested multi-line strings is not convenient without using template engines like jinja2, but in the end machine on the other end of transmission wouldn't care how good it looks if it expects plain old JSON.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.6k users

...