how to write GameObject position in the Scene to json file ?

on Clicking the button, I m loading the function WriteJsonForLevel(). I have placed three GameObject with the tag name “RedCoin” and I want to write the position of the GameObject to a JSON file. I can get the position of the object, but it’s all overwritten.I can only see the last GameObject position (i.e the completion of the loop)
[180371-sceneview.jpg*|180371]

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;

public class Writedatajsonfile : MonoBehaviour
{
       
    public List<GameObject> levelObjects;
    public string level;
    public Vector3 pos;

    // Start is called before the first frame update
    void Start()
    {
        levelObjects = new List<GameObject>();
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
    public void WritejsonForAll()
    {
        WriteJsonForLevel();
    }
    public void WriteJsonForLevel()
    {
     
       /* FileStream fs = new FileStream(Application.dataPath + "/sample.json",FileMode.Create);
        StreamWriter writer= new StreamWriter(fs);*/
        GameObject[] coinObjRed = GameObject.FindGameObjectsWithTag("RedCoin");
        putAllObjectInList(coinObjRed);
      
        
      
        
    }
    public void putAllObjectInList(GameObject[] p)
    {
        string path = Application.dataPath + "/text.json";
       foreach (GameObject q in p)
        {
            levelObjects.Add(q);
        }
        for (int i = 0; i < levelObjects.Count; i++)
        {
            GameObject lvlObj = levelObjects*;*
 *Vector3 pos = lvlObj.transform.position;*
 *string posOutput = JsonUtility.ToJson(pos);*
 *File.WriteAllText(path,posOutput);*
 *Debug.Log("position:" + posOutput);*
 
 *}*
 *}*
*}*
*```*
 *

The issue your running into is that File.WriteAllText() opens the file, writes to it and then closes the file. Every iteration of your loop overwrites the previous iteration. You will need to put all the pos into a single List or Array and pass that as json to File.WriteAllText() after the loop completes. This is a simplified example:

using System.Collections; 
using System.Collections.Generic; 
using UnityEngine; 
using System.IO;

public class Writedatajsonfile : MonoBehaviour
{
	public void WriteJsonForLevel()
	{
        GameObject[] levelObjects = GameObject.FindGameObjectsWithTag("RedCoin");
		string path = Application.dataPath + "/text.json";
		ListSerializer pos = new ListSerializer();
		for (int i = 0; i < levelObjects.Length; i++)
		{
			pos.posList.Add(levelObjects*.transform.position);*
  •  }*
    
  •  string posOutput = JsonUtility.ToJson(pos);*
    
  •  File.WriteAllText(path, posOutput);*
    
  •  Debug.Log("position:" + posOutput);*
    
  • }*
    }
    [Serializable]
    public class ListSerializer
    {
  • public List posList = new List();*
    }