为了账号安全,请及时绑定邮箱和手机立即绑定

将 JSON 传递给 C# python 进程

将 JSON 传递给 C# python 进程

PHP
桃花长相依 2024-01-20 21:46:46
我有一个小问题。我想从 C# 启动一个 python 进程,并且需要向它传递一些数据。数据是 json 格式,但如果我从 c# 序列化数据,它看起来像这样"[{\"SearchTerm_id\":1,\"Term\":\"lorem 本身\"},{\"SearchTerm_id\":2,\"Term\":\"lorem 本身\"}]}"由于双引号的分隔符,因此对 python 无效。如何将数据从 C# 传递到 python 脚本?这是我的代码:List<SearchTerms> searchTerms = await _context.SearchTerms.ToListAsync();var json = JsonConvert.SerializeObject(searchTerms);ProcessStartInfo processInfo = new ProcessStartInfo();string scriptPath = Path.Combine(System.IO.Directory.GetCurrentDirectory(), "Python\\scrapeGoogle.py");processInfo.FileName = "python3";processInfo.Arguments = string.Format("{0} {1}", scriptPath, json);processInfo.UseShellExecute = false;processInfo.CreateNoWindow = true;processInfo.RedirectStandardOutput = true;processInfo.RedirectStandardError = true;process.StartInfo = processInfo;process.Start();
查看完整描述

3 回答

?
Cats萌萌

TA贡献1805条经验 获得超9个赞

var json = JsonConvert.SerializeObject(searchTerms);如果您正在调试器中查看结果。调试器仅显示\作为视觉辅助,表示字符串,就像必须用 C# 编写一样。

尝试运行Console.Write(json);并查看输出。

输出将不包含转义字符。这才是真正的价值。


查看完整回答
反对 回复 2024-01-20
?
浮云间

TA贡献1829条经验 获得超4个赞


你是对的。所以问题似乎出在别处,因为如果我的 python 中只有 print(sys.argv 1 ),我将收到如下数据:“[{SearchTerm_id:1,Term:Lorem ipsun},{SearchTerm_id:2,洛雷姆·伊普苏姆}]”

C# 实际上是在不使用转义字符的情况下格式化 JSON,这与原始问题所说的相反。所以它正在做它应该做的事情。如果打印文本,您会看到{"SearchTerm_id":1,"Term":"lorem ipsum"}

但是,Python 接收的 JSON不带双引号。从 Python 打印显示{SearchTerm_id:1,Term:lorem ipsum}. 当您json.loads使用错误的 JSON 进行调用时,它会抛出异常。

json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

看起来,当您Process.Start()在 C# 中调用时,shell 会从ProcessStartInfo.Arguments列表中的 JSON 中删除双引号。所以Python接收的参数不带双引号。

解决方案

在 C# 中,序列化后更新 JSON 字符串,以便转义双引号。这里有一些代码可以帮助解决这个问题。

using Newtonsoft.Json;

using System.Text;

public static class JsonHelper

{

    public static string ToJsonString(

        object obj,

        bool escapeDoubleQuotes = false)

    {

        string serialized = JsonConvert.SerializeObject(obj);

        if (escapeDoubleQuotes)

        {

            // e.g., '{"key":"value"}' -> '{\"key1\":\"value\"}'

            // Do this when need to pass json as cmd line arg via System.Diagnostics.Process. Else shell will strip the double quotes, so your new process might not know what to do with it

            serialized = serialized.Replace(@"""", @"\""");

        }


        return serialized;

    }

}

所以为了让他的原始代码工作,OP只需改变


var json = JsonConvert.SerializeObject(searchTerms);


var json = JsonHelper.ToJsonString(searchTerms, escapeDoubleQuotes: true);


查看完整回答
反对 回复 2024-01-20
?
收到一只叮咚

TA贡献1821条经验 获得超4个赞

您可以使用 messagePack 库。我设法以高性能在 python 和 c# 之间传递字符串和其他类型。



查看完整回答
反对 回复 2024-01-20
  • 3 回答
  • 0 关注
  • 55 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信