0

从这个数据对象转换我的 json 代码时遇到问题...

  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'] = [{}]

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

4

2 回答 2

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

那应该工作得很好。只有你必须添加稍微不同的属性。像这样:

t['timeline']['date'][0]['startDate'] = "2011,12,10"
                     ^^^
                     first element in the array
于 2013-05-19T21:39:08.087 回答
1

直接建立一个哈希:

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

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

于 2013-05-19T22:14:40.970 回答