skip to Main Content

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


  1. Chosen as BEST ANSWER

    I've passed the arguments as follows and I'm not sure that this is the best solution but it works

    psi.Arguments = $""{script}" "{JsonConvert.SerializeObject(x)}"";
    

  2. Try passing like below :

       List<Item> jsonObject = new List<Item>
        {
                
                new Item { Name = "key1", Value = "value1" },
                new Item { Name = "key2 ", Value = "value2" }
        };
    
    
        using Newtonsoft.Json;
       
        
        string jsonString = JsonConvert.SerializeObject(itemList, Formatting.Indented);
    

    In you process in C# try passing like below :

    ProcessStartInfo startInfo = new ProcessStartInfo
        {
            FileName = pythonPath,
            Arguments = $"{scriptPath} "{JsonConvert.SerializeObject(jsonString)}"", // Pass JSON string as an argument
            RedirectStandardOutput = true,
            UseShellExecute = false,
            CreateNoWindow = true
        };
    
        using (Process process = new Process { StartInfo = startInfo })
        {
            process.Start();
            process.WaitForExit();
        }
    

    In your python code :

    import sys
    import json
    
    json_string = sys.argv[1]
    
    json_object = json.loads(json_string)
    
    print(json_object['key1'])
    print(json_object['key2'])
    

    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 :

        {
        "path":"C:\Users\user\Documents\myfile.txt",
        "models":[
           {"Id":5014,"Name":"e","Type":2},
           {"Id":2,"Name":"r1","Type":1}
          ]
        }
    

    This is VALID :

    {
      "path": "C:\Users\user\Documents\myfile.txt",
      "models": [
        {
          "Id": "5014",
          "Name": "e",
          "Type": "2"
        },
        {
          "Id": "2",
          "Name": "r1",
          "Type": "1"
        }
      ]
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search