简体   繁体   English

在 Python 中复制特定的 C# 脚本

[英]Replicating a specific C# script in Python

Apologies in advance for any formatting issues;对于任何格式问题,请提前道歉; first question posted here.第一个问题在这里发布。

I have a C# script that consists of 3 lines of code:我有一个由 3 行代码组成的 C# 脚本:

var json = File.ReadAllText("input.json");
var jsonObject = JsonSerializer.Deserialize<object>(json);
var newJson = JsonSerializer.Serialize(jsonObject);

This code is being used to take a JSON file of the form:此代码用于获取以下格式的 JSON 文件:

[
{
    "fileName": "File Name",
    "productType": "custom-csv",
    "requestSchema": {
        "includeTags": true,
        "fields": [
            {
                "header": "header",
                "valueType": "static",
                "value": "value"
            },
            ...
        ]
    }
},
{
}, ...
]

flatten it, and create a string that escapes the quotes.展平它,并创建一个转义引号的字符串。 The output looks like this:输出如下所示:

"[{\"fileName\":\"File Name\",\"productType\":\"custom-csv\",\"requestSchema\":{\"includeTags\":true,\"fields\":[{\"header\":\"Header\",\"valueType\":\"static\",\"value\":\"Value\"},...}]}},{}...]"

The way it is used is running the C# project in Debug with a break after newJson, copying the value from newJson when it hits the break, and then pasting it into a Seed file in another C# project to create a migration using Entity Framework to a SQL DB.它的使用方式是在 Debug 中运行 C# 项目并在 newJson 之后中断,当它遇到中断时从 newJson 复制值,然后将其粘贴到另一个 C# 项目的种子文件中,以使用实体框架创建迁移到SQL 数据库。

This is obviously clunky, and in order to share this with other people on my team, I want to reproduce this effect in a Python Script, which we would normally use for tasks like this.这显然很笨拙,为了与我团队中的其他人分享,我想在 Python 脚本中重现这种效果,我们通常将其用于此类任务。 I cannot seem to reproduce the output here so that the Seed file will be properly formatted.我似乎无法在此处重现输出,以便正确格式化种子文件。

After multiple attempts, my Python code looks like this:经过多次尝试,我的 Python 代码如下所示:

def parse_json(inputFile):
    with open(inputFile, 'r') as input:
        object = input.readlines()
    jsonData = json.dumps(object)
    outputFile = r"test.txt"
    with open(outputFile, 'w') as output:
        output.write(jsonData)

and the output looks like this:输出如下所示:

["[\n", "    {\n", "        \"fileName\": ...

I'm fairly new to writing Python, and I've done lots of searches both here and elsewhere to see what I'm missing, but I haven't been able to make much headway.我对编写 Python 还很陌生,我在这里和其他地方都做了很多搜索,看看我缺少什么,但我一直没能取得很大进展。

I'm open to alternative solutions, but I cannot change the end goal: obtain a string that I can past into the Seed File in a C# project for creating a migration.我对替代解决方案持开放态度,但我无法更改最终目标:获取一个字符串,我可以将其传递到 C# 项目中的种子文件中以创建迁移。 It needs to be formatted properly to do that, and I'd like to avoid my current solution.它需要正确格式化才能做到这一点,我想避免我目前的解决方案。 It seems like this should be possible with Python, but I cannot figure it out.似乎这应该可以用 Python 实现,但我无法弄清楚。

Thanks in advance.提前致谢。

Once the json is loaded you can cast it to string and use a str.replace .加载 json 后,您可以将其转换为字符串并使用str.replace

# j from JSON
j = [{'fileName': 'File Name', 'productType': 'custom-csv', 'requestSchema': {'includeTags': True, 'fields': [{'header': 'header', 'valueType': 'static', 'value': 'value'}]}}, {}]

# cast to string
json_as_string = str(j)
# return: "[{'fileName': 'File Name', 'productType': 'custom-csv', 'requestSchema': {'includeTags': True, 'fields': [{'header': 'header', 'valueType': 'static', 'value': 'value'}]}}, {}]"

# replace ' with \". Remark: Python escapes with \ thats why the result has double backslashes.
json_as_string.replace("'", r'\"')
# dump new string to json will add another backslash
with open(r"C:\Temp\test.json", "w") as t:
    json.dump(json_as_string.replace("'", r'\"'), t)

Are additional backslashes a problem for the SQL DB?额外的反斜杠对 SQL DB 来说是个问题吗?

Side note: overwriting a reserved name might cause problems if you plan using it after re-assigning it.旁注:如果您打算在重新分配后使用保留名称,则覆盖保留名称可能会导致问题。 Like if you overwrite input and want to use it later to read user input it will not work as expected.就像您覆盖input并希望稍后使用它来读取用户输入一样,它将无法按预期工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM