Embedding JSON Data into YAML file

后端 未结 5 1974
孤城傲影
孤城傲影 2020-12-13 16:52

I am writing a fixture for my table. And a one of the coloums takes in a JSON string as a value.

The problem is the fixture is not loading failing as:



        
相关标签:
5条回答
  • 2020-12-13 17:32

    In my table, the column stripe_connect is of type JSONB . In the fixture, here is what worked. Note that the outer single-quotes are necessary, but square brackets are not. Everything between the single quotes is one long line.

     stripe_connect: '{"scope":"read_write", "livemode":false, "token_type":"bearer", "access_token":"sk_test_madeupvalue", "refresh_token":"rt_Ae29madeupvalueyX", "stripe_user_id":"acct_103yZabcdefg", "stripe_publishable_key":"pk_test_0HEOmadeupvalue"}'
    
    0 讨论(0)
  • 2020-12-13 17:43

    I believe taking it into quotes should do the trick:

    portslist: '[{"name":"ob1","port_type" ... }]'
    
    0 讨论(0)
  • 2020-12-13 17:43

    clarkevans' comment on the accepted answer suggested a better answer for long bits of JSON, because you can wrap the lines. I looked up the block scalar syntax he mentioned, and thought I would include an example here:

    portslist: >
      [{"name":"ob1","port_num":0,"port_type":"network"},
      {"name":"ob2","port_nu...
    
    0 讨论(0)
  • 2020-12-13 17:44

    For the sake of being complete: In case you're using ActiveRecord::Store, you can load your data simply using YAML representation of the same data, even if it is a JSON store:

    one:
      portslist:
        - 
          name: 'ob1'
          port_num: 0
          port_type: 'network'
        - 
          name: 'ob2'
          port_num: 1
          port_type: 'network'
    
    0 讨论(0)
  • 2020-12-13 17:59

    If you have the string, you can use as simple as Vlad Khomich mentioned:

    portslist: '[{"name":"ob1","port_num":0,"port_type":"network"},...]'
    

    If you are using ERB and have an object, you can use to_json and inspect to escape to a JSON string:

    portslist: <%= [{name: 'ob1', port_num: 0, port_type: 'network'},...].to_json.inspect %>
    

    And if you have a large JSON specification, you can store it in a separated file and load using Ruby, so you can keep your YAML file clean:

    portslist: <%= File.read('/path/to/file.json').inspect %>
    
    0 讨论(0)
提交回复
热议问题