How can I write to / make changes in a json file?

I’m reading in a JSON file, deserializing, and now I want to make a change if a value doesn’t exist for example and save it back to the original file. Having trouble finding information about this much of the json forum posts are about parsing.

2 Likes

Hello @Rashan_Arshad,

What do you think about this?

  1. Read JSON file
  2. Deserialize
  3. Make changes into JObject
  4. Serialize JObject after changes. For this, you can use → Newtonsoft.Json.JsonConvert.SerializeObject(variable)
  5. Use “Create file” activity, providing same name and path. This will replace old json file by a new blank json file.
  6. Use “Append Line” to write the new json content from the fourth step, to the new json file

If you think it is reasonable, please test it and let me know if it worked.

I actually figured it out and did something very similar, I just used assign activity instead for step 4. but thank you!

1 Like
  1. Make changes into JObject.

This is the step. Tried bit everything.

How you are able to modify single JObject ( as a reference) Attributes/Values to keep it in entact to be serialized back to string?

Like this? JObjectData.SelectToken(“value”).First().SelectToken(“UserName”) = “newUserName”

1 Like

Hi @Drop_Mouse,

Let’s say you have JSON file below:

{
  "name": "BlankProcess1",
  "description": "Blank Process",
  "main": "Main.xaml",
  "runtimeOptions": {
    "autoDispose": false,
    "isPausable": true,
    "requiresUserInteraction": true,
    "supportsPersistence": false,
    "excludedLoggedData": [
      "Private:*",
      "*password*"
    ],
    "executionType": "Workflow",
    "readyForPiP": false,
    "startsInPiP": false
  }
}

This would be enough:

image (1)

In this case, “Workflow” value from “runtimeOptions.executionType” property would be changed to “Changed”

Then, you proceed to step 4 (Serialize JObject after changes)

If you have a different JSON structure and are having troubles to solve, kindly share your json file or part of it (don’t need to be real values due to privacy issues).

2 Likes

Hello @gustavo.cervelin Great piece of information! I have some questions…

What if I would like to add new attributes/tokens?

Why do you serialize again after editing?

Thank you very much.

1 Like

Just give yourJSONObj.ToString as the input to a Write Text File activity.

Then you use the various JSON methods like JObject.Add to add what you want.

You don’t have to. You can just .ToString it.

Here is an example of code I have in an Invoke Code to build my JSON object before I write it to a text file.

Dim jMain As JObject = New JObject

'add header section
jMain.Add("$schema","http://json-schema.org/draft-07/schema")
jMain.Add("$id","http://example.com/example.json")
jMain.Add("type","object")
jMain.Add("title",schemaTitle)
jMain.Add("description",schemaDescription)

'add default section
Dim jDefault As JObject = New JObject
jMain.Add("default",jDefault)

'build examples, required, properties
Dim jExample As JObject = New JObject
Dim jRequired As JArray = New JArray
Dim jProperties As JObject = New JObject
For Each CurrentRow As DataRow In DT_Properties.AsEnumerable
	'add to required section
	If CBool(CurrentRow("Required").ToString) Then
		jRequired.Add(CurrentRow("Field_Name").ToString)
	End If
	
	'build property
	Dim jProperty As JObject = New JObject
	Dim jPropertyExamples As JArray = New JArray
	jProperty.Add("$id","#/properties/" + CurrentRow("Field_Name").ToString)
	jProperty.Add("type",CurrentRow("Datatype").ToString)
	jProperty.Add("title","The " + CurrentRow("Field_Name").ToString + " schema")
	jProperty.Add("description",CurrentRow("Field_Name").ToString)
	Select Case CurrentRow("Datatype").ToString
	Case "string"
		JExample.Add(CurrentRow("Field_Name").ToString,CurrentRow("Example_Value").ToString)
		jPropertyExamples.Add(CurrentRow("Example_Value").ToString)
		If Not (CurrentRow("String_Format").ToString = "none" Or String.IsNullOrEmpty(CurrentRow("String_Format").ToString)) Then
			jProperty.Add("format",CurrentRow("String_Format").ToString)
		End If
	Case "integer"
		If Not String.IsNullOrEmpty(CurrentRow("Example_Value").ToString) Then
			JExample.Add(CurrentRow("Field_Name").ToString,CInt(CurrentRow("Example_Value").ToString))
			jPropertyExamples.Add(CInt(CurrentRow("Example_Value").ToString))
		End If
	End Select
	jProperties.Add(CurrentRow("Field_Name").ToString,jProperty)
	
	
	jProperty.Add("examples",jPropertyExamples)
Next
Dim jExamples As JArray = New JArray
jExamples.Add(jExample)
jMain.Add("examples",jExamples)
jMain.Add("required",jRequired)
jMain.Add("properties",jProperties)
jMain.Add("additionalProperties",additionalProperties)
schemaJSONStr = jMain.ToString
1 Like

I get it! thank you @postwick
Where would you search first if you needed to investigate about JSON methods? Just curious :face_with_monocle:

Thank you

Google. JSON isn’t specific to UiPath. You’ll just use the standard JSON methods. Also refresh this page to see the code I added to my last comment.

Thanks @postwick :grinning: I actually asked chatgpt to explain to me the whole code, (since i dont have actual programming background) very interesting. Could you share the final json you obtain? as text.

Hope Im not asking too much, thank you!

It actually results in a JSON schema which is another standard thing outside UiPath (but is used in Orchestrator to control what data is inside a queue item).

Here is an example of the kind of output it gives you:

{
  "$schema": "http://json-schema.org/draft-07/schema",
  "$id": "http://example.com/example.json",
  "type": "object",
  "title": "Specific Content schema",
  "description": "The schema for the XXXX-Dept-Name automation",
  "default": {},
  "examples": [
    {
      "Customer Name": "Example string",
      "Account Number": 4,
      "Email Address": "someone@somecompany.com",
      "City": "Example string",
      "State": "Example string",
      "Zip Code": "Example string"
    }
  ],
  "required": [
    "Customer Name",
    "Account Number",
    "Email Address"
  ],
  "properties": {
    "Customer Name": {
      "$id": "#/properties/Customer Name",
      "type": "string",
      "title": "The Customer Name schema",
      "description": "Customer Name",
      "examples": [
        "Example string"
      ]
    },
    "Account Number": {
      "$id": "#/properties/Account Number",
      "type": "integer",
      "title": "The Account Number schema",
      "description": "Account Number",
      "examples": [
        4
      ]
    },
    "Email Address": {
      "$id": "#/properties/Email Address",
      "type": "string",
      "title": "The Email Address schema",
      "description": "Email Address",
      "format": "email",
      "examples": [
        "someone@somecompany.com"
      ]
    },
    "City": {
      "$id": "#/properties/City",
      "type": "string",
      "title": "The City schema",
      "description": "City",
      "examples": [
        "Example string"
      ]
    },
    "State": {
      "$id": "#/properties/State",
      "type": "string",
      "title": "The State schema",
      "description": "State",
      "examples": [
        "Example string"
      ]
    },
    "Zip Code": {
      "$id": "#/properties/Zip Code",
      "type": "string",
      "title": "The Zip Code schema",
      "description": "Zip Code",
      "examples": [
        "Example string"
      ]
    }
  },
  "additionalProperties": false
}
1 Like

Note that any time you see something inside [ ] that means it’s a JArray. So you add your values to the array first, then add the array to the main object.

Dim myJObject As JObject = New JObject
Dim myJArray As JArray = New JArray
myJArray.Add("value1")
myJArray.Add("value2")
myJObject.Add("array property name",myJArray)

Hi @Luis_Fernando,

I see that @postwick has already helped you.

If you have any questions, just let me know.

Thanks guys!

Hello @gustavo.cervelin
Lets say I have this json which is the esqueleton for PULL calls that I would make throught my automation

{
“estado”: “error-proceso”,
“error”: true,
“mensaje”: “No se encontró el numero de vuelo”,
“informacionProceso”: {
“totalFilas”: 3106,
“filasProcesadas”: 0,
“filasError”: 20
}
}

How can I store this Json y a JsonObj variable?

1 Like

Hello @Luis_Fernando

You can create a simple text file (.txt) with this json esqueleton you mentioned above.

Note: Use straight double quotes ("). DO NOT use curly ones ( )

Use a read text file activity and store the value in a String variable.

Use a deserialize json activity providing the json as string as input and store the JObject as output. If you are not able to select the variable type as JObject, install the UiPath.WebAPI.Activities

Find below some screenshots that may help you.

image

image

Hope it helps :slight_smile:

But we If I want to harcode the json esqueleton in the workflow?
Because I could achieve the same result as you did but using an input dialog, but Im trying to figure out a way to leave it inside flow without intervention of other sources besides the flow itself.
Storing the json in a string variable is hard because of the double quotes.
Yet your solution is a very valid one and I ight use it, but still Im trying to dig even more.

1 Like

Store it in a variable then use Assign yourJSONObjVar = JObject.Parse(yourJSONStrVar)

{‘key’:‘name’} is valid JSON, it doesn’t have to be double quotes.

But how can I store it initially in the string?