yj icon indicating copy to clipboard operation
yj copied to clipboard

Conversion of HCL to/from JSON

Open nj2208 opened this issue 2 years ago • 3 comments

Hi

Have one query regarding conversion of HCL to/from JSON . Conversion from HCL to JSON seems fine however while converting back the generated json to HCL it is not same . As seen in the example below docker_ports was single element of type list / array when converted to json whereas when it is converted back to HCL from from json , docker_ports is represented as two elements instead of two .Any idea why it was not exactly same as orignal HCL after conversion? Any way to get back same HCL format ?

Original tfvars file

image_id = "ami-123"

cluster_min_nodes = 2

cluster_decimal_nodes = 2.2

cluster_max_nodes = true

availability_zone_names = [
  "us-east-1a",
  "us-west-1c",
]

docker_ports = [{
  internal = 8300
  external = 8300
  protocol = "tcp"
},
{
  internal = 8301
  external = 8301
  protocol = "tcp"
}
] 

Conversion of HCL to json

$ ./yj-linux-amd64 -cj < testing.tfvars

{
  "image_id": "ami-123",
  "cluster_min_nodes": 2,
  "cluster_decimal_nodes": 2.2,
  "cluster_max_nodes": true,
  "availability_zone_names": [
    "us-east-1a",
    "us-west-1c"
  ],
  "docker_ports": [
    {
      "internal": 8300,
      "external": 8300,
      "protocol": "tcp"
    },
    {
      "internal": 8301,
      "external": 8301,
      "protocol": "tcp"
    }
  ]
}

JSON to HCL conversion

/yj-linux-amd64 -jc < testing.tfvars.json
"availability_zone_names" = ["us-east-1a", "us-west-1c"]

"cluster_min_nodes" = 2

"docker_ports" = {
  "external" = 8300

  "internal" = 8300

  "protocol" = "tcp"
}

"docker_ports" = {
  "external" = 8301

  "internal" = 8301

  "protocol" = "tcp"
}

"image_id" = "ami-123"

Thanks a lot !

nj2208 avatar Mar 22 '23 15:03 nj2208

JSON to HCL is, indeed, broken.

{
  "map": {
    "a": "1",
    "b": "2",
    "c": "3"
  }
}

gets converted to

"map/a" = "1"

"map/b" = "2"

"map/c" = "3"

which is wrong.

nikolay avatar Sep 26 '23 22:09 nikolay

@nikolay I can't seem to replicate your issue:

stephen@laptop test % yj -jc
{
  "map": {
    "a": "1",
    "b": "2",
    "c": "3"
  }
}
"map" = {
  "a" = "1"

  "b" = "2"

  "c" = "3"
}

@nj2208 the output you provided above is expected. This is how HCL1 represents multiple list items by default. There is no way to recover the original version, since that information is lost when the file is converted to JSON.

sclevine avatar Sep 26 '23 23:09 sclevine

@sclevine It was my fault, sorry! 🤦🏻 All is good, but it would be nice if the unnecessary quotes were not added so that HCL looks more natural. In general, any valid JSON file is a valid HCL, so there is no need to do anything, but the value of this tool is to generate something more useful.

nikolay avatar Sep 27 '23 21:09 nikolay