2013-05-19 83 views
0

有一個問題,我的翻譯JSON代碼形式此dataObject時...如何正確格式化此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'] = [{}] 

我應該如何正確寫出這些行?

回答

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

這應該工作得很好。只有你必須添加略有不同的屬性。就像這樣:

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

就直接建一個哈希:

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

節省了大量的打字,而且會精神上更加自然地映射到JSON。

+0

你的哈希語法無效:) –

+0

Doh,它是。不過,點站立。 :) –

+0

nope ....這給...「語法錯誤,意外的'=',期待tASSOC」 – thefonso