I’m trying to pass JSON object to python script through process but the script receives the JSON object in a wrong format the keys of the object without double or single quotes like the following:
{path:C:\Users\user\Documents\myfile.txt,models:[{Id:5014,Name:e,Type:2},{Id:2,Name:r1,Type:1}]}
C# process code:
var script = "D:\python\pythonscript.py";
var objectJson = new ObjectJson()
{
path = "C:\Users\user\Documents\myfile.txt",
models = models
};
var x = JsonConvert.SerializeObject(objectJson);
Console.WriteLine(x);
psi.Arguments = $""{script}" """{x}"""";
Console.WriteLine(psi.Arguments);
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
var errors = "";
var results = "";
using (var process = Process.Start(psi))
{
errors = process.StandardError.ReadToEnd();
results = process.StandardOutput.ReadToEnd();
process.WaitForExit();
}
Josn object in C# code is :
{"path":"C:\Users\user\Documents\myfile.txt","models":[{"Id":5014,"Name":"e","Type":2},{"Id":2,"Name":"r1","Type":1}]}
Python code gives me error at data.models that there is no attribute called models in data
dataObj = sys.argv[1]
data = json.loads(dataObj)
models = data.models
When passing process arguments like the following:
psi.Arguments = $""{script}" "{x}"";
python script gives an error at line json.loads(dataObj) that json decoder can’t convert it to json cause it expect name between double quotes.
Any idea how to solve this?
2
Answers
I've passed the arguments as follows and I'm not sure that this is the best solution but it works
Try passing like below :
In you process in C# try passing like below :
In your python code :
Check if the values key1 and key2 were received without any error. If so you can create a class Serialize object in C# properly and pass it to the shell script.
What happens is that python actually complains that it is not valid JSON. In your case This is NOT VALID :
This is VALID :