2

Can somebody clarify how to access the object’s property inside the action? object.property or $object.property or ${object.property} or ${{object.property}} don’t work.

I created an object from the data from the JSON file using fromJson() method:

  - name: "Get env data"
    id: get_env_data
    run: |
      JSON=$(jq --arg inputEnv "${{ github.event.inputs.env_to_deploy }}" 'map(. | select(.deployEnv==$inputEnv) ) | .[0]' .github/workflows/test.json)
      JSON="${JSON//$'\n'/''}"
      JSON="${JSON//$'\r'/''}"
      JSON="${JSON//$'\s+'/''}"
      echo "JSON=$JSON"
      echo "::set-output name=deployment_env::$JSON"
    
  - name: "Set env data"
    run: |
      env_data=${{ fromJson(steps.get_env_data.outputs.deployment_env) }}
      echo "env_data=$env_data"
      echo $env_data.port

The JSON file is like that:

[
    {
        "env":"dev",
        "port":"8000",
        "db_host":"DEV_DB_HOST"
    },
    {
        "env":"dev2",
        "port":"8002",
        "db_host":"DEV2_DB_HOST"
    },
    {
        "env":"dev3",
        "port":"8003",
        "db_host":"DEV3_DB_HOST"
    }
]
michael
  • 91
  • 2
  • 6
  • Seems a lot similar to [this question](https://stackoverflow.com/questions/61919141/read-json-file-in-github-actions). Did you try using directly: `echo "${{fromJson(steps.get_env_data.outputs.deployment_env)}}"` to see if the json is retrieved correctly? It's seems to be possible to use directly something like this as well: ``echo "${{fromJson(steps.get_env_data.outputs.deployment_env).[0].port}}"`` (as it's a list, I don't think you will be able to access directly the port without informing the position). – GuiFalourd Jul 28 '21 at 13:00
  • As result, I received valid JSON as an object and not an array (| .[0] does this job). echo "JSON=$JSON" outputs correct JSON. echo $env_data.port - Object.port – michael Jul 28 '21 at 14:06
  • If you use directly `echo "${{fromJson(steps.get_env_data.outputs.deployment_env).port}}"` as first command of the `Set env data` step. Does it work? – GuiFalourd Jul 28 '21 at 14:23
  • Yes, it displays a correct port number. – michael Jul 28 '21 at 16:52
  • I don't think it's possible to get the whole object that way on GHA, instead on extracting only a field value from the JSON each time. A workaround would be to extract all fields in different env variables to access them afterwards, but clearly it's not the nicest solution. – GuiFalourd Jul 28 '21 at 16:57

1 Answers1

1

Unfortunately, I couldn't manage to solve this issue properly. I chose this way to get properties from the JSON as @GuiFalourd suggested and many examples I saw:

PORT=${{fromJson(steps.get_env_data.outputs.deployment_env).port}}
michael
  • 91
  • 2
  • 6