Inserting JSON and saving new values

PROJECT STATUS:

I was able to create an initial json object, insert values into it and save it.

Now I want to add a new entry to it and save that, and so on, and so on. WriteAllText will overwrite the current file. I’ve tried AppendAll, which kinda works, but I’d had some odd results. One field would save old data even after the variable values were changed.

public string GroupName="6th Batalion";
	public string GroupMemberID="TG";
	public string GroupMemberName="Tommy Gun";
	public string GroupEquipmentID="TG1";
	public string GroupEquipmentDescription="AR-9 machine gun";


void Start () 
	{
		Testjson();
	}
	
	public void Testjson()
	{
		var groupdata = new JSONObject
		{
			{"GroupID", GroupID},
			{"GroupMemberName" , GroupMemberName},

		};

		var equipmentdata = new JSONObject
		{
				{"EquipmentID" , GroupEquipmentID},
			 	{"EquipmentDescription" , GroupEquipmentDescription},
				
		};

		var maindata = new JSONObject
		{
			{"Group Name" , GroupName},
			{"Group Member" , groupdata},
			{"Group Equipment" , equipmentdata}
		};



		//return maindata;
		Debug.Log(maindata);
		File.WriteAllText(Application.dataPath + "/bandtest.json", maindata.ToString()); 

	}

Results: {“Group Name”:“6th Batalion”,“Group Member”:{“GroupMemberID”:“TG”,“GroupMemberName”:“Tommy Gun”},“Group Equipment”:{“EquipmentID”:“TG1”,“EquipmentDescription”:“AR-9 machine gun”}}
Works great here!
Now we change the variables
public string GroupName=“6th Batalion”;
public string GroupMemberID=“STF”;
public string GroupMemberName=“SpikeHawk ThunderFist”;
public string GroupEquipmentID=“STF1”;
public string GroupEquipmentDescription=“Vulcan Cannon”;

What’s the best way to save the new data and keep the old data?
Do I make two separate json files and create a third with all of them?
Thanks!

Parse old data, make changes, serialize, save.

Also, You shouldn’t combine path like this (#48):

File.WriteAllText(Application.dataPath + "/bandtest.json", maindata.ToString());

But instead use System.IO.Path.Combine(). Also, Application.persistentDataPath is the “right place” to save data.

var path = System.IO.Path.Combine(Application.persistentDataPath, "bandtest.json");
File.WriteAllText(path, maindata.ToString());