如何正确格式化这个json?

时间:2013-05-19 21:35:09

标签: ruby json

在翻译我的json代码时出现问题形成了这个dataObject ...

  var dataObject = {
      "timeline":
      {
          "headline":"The Main Timeline Headline Goes here",
          "type":"default",
          "text":"<p>Intro body text goes here, some HTML is ok</p>",
          "asset": {
              "media":"http://yourdomain_or_socialmedialink_goes_here.jpg",
              "credit":"Credit Name Goes Here",
              "caption":"Caption text goes here"
          },
          "date": [
              {
                  "startDate":"2011,12,10",
                  "endDate":"2011,12,11",
                  "headline":"Headline Goes Here",
                  "text":"<p>Body text goes here, some HTML is OK</p>",
                  "asset": {
                      "media":"http://twitter.com/ArjunaSoriano/status/164181156147900416",
                      "thumbnail":"optional-32x32px.jpg",
                      "credit":"Credit Name Goes Here",
                      "caption":"Caption text goes here"
                  }
              }
          ],
          "era": [
              {
                  "startDate":"2011,12,10",
                  "endDate":"2011,12,11",
                  "headline":"Headline Goes Here",
                  "text":"<p>Body text goes here, some HTML is OK</p>",
              }
          ]
      }
  }

进入这种方法...

def timeline     
  t = {}
  t['timeline'] = {}
  t['timeline']['headline'] = "Lorem"
  t['timeline']['text'] = "default"
  t['timeline']['asset'] = {}
  t['timeline']['asset']['media'] = ""
  t['timeline']['asset']['credit'] = ""
  t['timeline']['asset']['caption'] = ""

  t['timeline']['date'] = [{}]
  t['timeline']['date']['startDate'] = "2011,12,10"
  t['timeline']['date']['endDate'] = "2011,12,11"
  t['timeline']['date']['headline'] = ""
  t['timeline']['date']['text'] = ""
  t['timeline']['date']['asset'] = {}
  t['timeline']['date']['asset']['media'] = ""
  t['timeline']['date']['asset']['thumbnail'] = ""
  t['timeline']['date']['asset']['credit'] = ""
  t['timeline']['date']['asset']['caption'] = ""

  t['timeline']['era'] = [{}]
  t['timeline']['era']['startDate'] = "2011,12,10"
  t['timeline']['era']['endDate'] = "2011,12,11"
  t['timeline']['era']['headline'] = ""
  t['timeline']['era']['text'] = ""

  return t
end

特别是我不确定

t['timeline']['date'] = [{}]

t['timeline']['era'] = [{}]

我应该如何正确地写这些线?

2 个答案:

答案 0 :(得分:1)

t['timeline']['date'] = [{}]

应该可以正常工作。只需要添加略有不同的属性。像这样:

t['timeline']['date'][0]['startDate'] = "2011,12,10"
                     ^^^
                     first element in the array

答案 1 :(得分:1)

直接构建哈希:

def timeline
  {
    "timeline" = {
      "headline" = "Lorem",
      "text" = "default",
      "asset" = {}
    },
    "date" = [{
      "startDate" = "2011,12,10",
      "asset" = {
        "media" = ""
      }
    }]
  }
end

保存了大量的输入,并且会更自然地映射到JSON。