YAML equivalent of array of objects in JSON

后端 未结 2 412
遇见更好的自我
遇见更好的自我 2020-12-22 20:10

I have a JSON array of objects that I\'m trying to convert to YAML.

{\"AAPL\": [
  {
    \"shares\": -75.088,
    \"date\": \"11/27/2015\"
  },
  {
    \"sh         


        
相关标签:
2条回答
  • 2020-12-22 20:51

    TL;DR

    You want this:

    AAPL:
      - shares: -75.088
        date: 11/27/2015
      - shares: 75.088
        date: 11/26/2015
    

    Mappings

    The YAML equivalent of a JSON object is a mapping, which looks like these:

    # flow style
    { foo: 1, bar: 2 }
    
    # block style
    foo: 1
    bar: 2
    

    Note that the first characters of the keys in a block mapping must be in the same column. To demonstrate:

    # OK
       foo: 1
       bar: 2
    
    # Parse error
       foo: 1
        bar: 2
    

    Sequences

    The equivalent of a JSON array in YAML is a sequence, which looks like either of these (which are equivalent):

    # flow style
    [ foo bar, baz ]
    
    # block style
    - foo bar
    - baz
    

    In a block sequence the -s must be in the same column.

    JSON to YAML

    Let's turn your JSON into YAML. Here's your JSON:

    {"AAPL": [
      {
        "shares": -75.088,
        "date": "11/27/2015"
      },
      {
        "shares": 75.088,
        "date": "11/26/2015"
      },
    ]}
    

    As a point of trivia, YAML is a superset of JSON, so the above is already valid YAML—but let's actually use YAML's features to make this prettier.

    Starting from the inside out, we have objects that look like this:

    {
      "shares": -75.088,
      "date": "11/27/2015"
    }
    

    The equivalent YAML mapping is:

    shares: -75.088
    date: 11/27/2015
    

    We have two of these in an array (sequence):

    - shares: -75.088
      date: 11/27/2015
    - shares: 75.088
      date: 11/26/2015
    

    Note how the -s line up and the first characters of the mapping keys line up.

    Finally, this sequence is itself a value in a mapping with the key AAPL:

    AAPL:
      - shares: -75.088
        date: 11/27/2015
      - shares: 75.088
        date: 11/26/2015
    

    Parsing this and converting it back to JSON yields the expected result:

    {
      "AAPL": [
        {
          "date": "11/27/2015", 
          "shares": -75.088
        }, 
        {
          "date": "11/26/2015", 
          "shares": 75.088
        }
      ]
    }
    

    You can see it (and edit it interactively) here.

    0 讨论(0)
  • 2020-12-22 21:04

    Great answer above. Another way is to use the great yaml jq wrapper tool, yq at https://github.com/kislyuk/yq

    Save your JSON example to a file, say ex.json and then

    yq -y '.' ex.json
    
    AAPL:
    - shares: -75.088
      date: 11/27/2015
    - shares: 75.088
      date: 11/26/2015
    
    0 讨论(0)
提交回复
热议问题