#Flatten YAML to JSON with Object support

4 messages · Page 1 of 1 (latest)

cobalt crag
#

Hi! I have a use case where I'm having a YAML file which I need to convert to JSON but with support of

  1. Joining/Flatten the keys via . - THis is doable
  2. Adding support of JSON objects as value.

Explaining 2nd case:

Consider this YAML

all:
  sticky:
    menu:
      toast: true
  appTheme:
    config: []
    enable: false
  brand:
    is_override_enabled: false
    x-cache-control: {"max-age": 300,"stale-while-revalidate": 300,"stale-if-error": 300}

  common:
    network:
      error_NET: { "message": "common-v2__network_security_error_message",
        "primary_cta": "common-v2__cta_retry",
        "secondary_cta": "common-v2__cta_help",
        "title": "common-v2__network_security_error_title" }

Here all.appTheme has a YAML based object where it has 2 keys i.e config and enable similarly all.common.network.error_NET also has a value as object but a JSON one. With the help of gopkg.in/yaml.v3" I unmarshall the YAML string but it cant identify the YAML vs JSON objects as value. What I want is, that JSON objects should be directly replaced as value and should not be flattened. Example:

{
  // NOTE THIS NOT FLATTENED AS VALUE IS A JSON OBJECT
  "all.common.error_NET": { "message": "common-v2__network_security_error_message",
        "primary_cta": "common-v2__cta_retry",
        "secondary_cta": "common-v2__cta_help",
        "title": "common-v2__network_security_error_title" }

  // NOTE THAT THIS GOT FLATTENED AS VALUE WAS A YAML OBJECT
  "all.appTheme.config": [],
  "all.appTheme.enable": false
}

I am unable to achieve this conversion, any ideas?

fleet creek
#

You can use this yaml library to decode a yaml object into a struct containing json tags, and then use json.RawMessage to keep the json in its raw form

cobalt crag
#

Got it, BTW what's the limitation with standard approach I mentioned? Why can't parser identify the inline YAML with JSON objects. It parses both of them as objects. The way it reads JSON I feel technicaly there isn't any limitation in that