2015-11-24 3 views
0

Моя проблема очень маленькая, но очень расстраивающая, так как я не могу получить ответ. Я пытаюсь получить доступ к части JSON ответа от Google Script. В Golang, мне удалось лишить его до этогоUnmarshal JSON в структуру

map[@type:type.googleapis.com/google.apps.script.v1.ExecutionResponse result:[ 
{ 
    "id": 1, 
    "casenumber": "Criminal Case 20 of 2012", 
    "datedelivered": "2015-10-22T21:00:00.000Z", 
    "judge": "George Matatia Abaleka Dulu", 
    "court": "High Court", 
    "location": "Garissa", 
    "accused": "Abdi Sheikh Mohamed", 
    "judgment": "The accused Abdi Sheikh Mohamed stands charged with the offence of murder contrary to Section 203 as read with Section 204 of the Penal Code. The particulars of the offence are that on 8th May 2012 at Ifo Refugee camp, Lagdera District within Garissa County murdered Othon Ubang Alwal. He has denied the charge." 
}, 
{ 
    "id": 2, 
    "casenumber": "Criminal Case 21 of 2012", 
    "datedelivered": "2015-11-22T21:00:00.000Z", 
    "judge": "Lilo", 
    "court": "High Court", 
    "location": "Nairobi", 
    "accused": "Stitch", 
    "prosecution": "Milo", 
    "judgment": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum" 
} 
]] 

, но мне нужно, чтобы лишить его вниз один уровень дальше, избавившись от

map[@type:type.googleapis.com/google.apps.script.v1.ExecutionResponse result:[ 

, так что я только часть результатов.

До сих пор я пробовал развязать его с моей структурой без успеха. Вот структура

type Case struct { 
    ID int    
    CaseNumber string 
    DateDelivered string 
    Judge string 
    Court string 
    Location string         
    Accused string 
    Prosecution string 
    Judgment string 
} 

Любая помощь будет высоко оценена.

EDIT: Что я имел в виду в демаршалинга части является то, что, когда я пытаюсь демаршалинга в моей структуры (даже после того, как фиксируя-структуру), я получаю ошибку

json: cannot unmarshal object into Go value of type []Case 

Это код, мне нужно, чтобы получить для работы http://play.golang.org/p/rmsvfPVx52.

+1

Когда вы говорите, что попробовали unmarshalling без успеха, можете предоставить более подробную информацию. Также вы можете показать свой код, который поможет понять, что вы пытаетесь. На данный момент я вижу, что для структуры Case, кроме ID, все остальные поля не отображаются, если они не начинаются с заглавных букв, и при их разборке они не будут заполнены. –

+0

Большое вам спасибо за это! Я не заметил. Проверьте вопрос по вопросу.Я использовал его, чтобы ответить на ваш вопрос :) – Mardwan

ответ

2

Вам необходимо указать export поля в Case, начав имя с символом верхнего регистра.

type Case struct { 
    ID int    
    CaseNumber string 
    DateDelivered string 
    Judge string 
    Court string 
    Location string         
    Accused string 
    Prosecution string 
    Judgment string 
} 

Пакет encoding/json и аналогичные пакеты игнорируют невыполненные поля.

Используйте кусочек для декодирования массив JSON:

var result []Case 
    err := json.Unmarshal(data, &result) 
    if err != nil { 
    // handle error 
    } 

Playground Example

+0

Большое вам спасибо за ответ. Уверен, что это решение сработает, если я смогу найти способ убрать 'map [@type: type.googleapis.com/google.apps.script.v1.ExecutionResponse result: [' автоматически использовать код, а не вручную. Возможно, я ошибаюсь :(Но посмотрите на это, пожалуйста, http://play.golang.org/p/rmsvfPVx52 – Mardwan

+1

Текст 'map [@type: type.googleapis.com/google.apps.script.v1 .ExecutionResponse' недействителен JSON. Вам нужно будет удалить вручную, если сервер действительно возвращает недопустимый JSON. –

+0

Спасибо. Мне жаль, что не было автоматизированного решения. – Mardwan

0

Где c является

map[@type:type.googleapis.com/google.apps.script.v1.ExecutionResponse result:[ 
{ 
"id": 1, 
"casenumber": "Criminal Case 20 of 2012", 
"datedelivered": "2015-10-22T21:00:00.000Z", 
"judge": "George Matatia Abaleka Dulu", 
"court": "High Court", 
"location": "Garissa", 
"accused": "Abdi Sheikh Mohamed", 
"judgment": "The accused Abdi Sheikh Mohamed stands charged with the offence of murder contrary to Section 203 as read with Section 204 of the Penal Code. The particulars of the offence are that on 8th May 2012 at Ifo Refugee camp, Lagdera District within Garissa County murdered Othon Ubang Alwal. He has denied the charge." 
}, 
{ 
"id": 2, 
"casenumber": "Criminal Case 21 of 2012", 
"datedelivered": "2015-11-22T21:00:00.000Z", 
"judge": "Lilo", 
"court": "High Court", 
"location": "Nairobi", 
"accused": "Stitch", 
"prosecution": "Milo", 
"judgment": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum" 
} 
]] 

я сделал;

case:= c.(map[string]interface {}) 
fmt.Println(case["result"]) 

который дает;

[ 
{ 
    "id": 1, 
    "casenumber": "Criminal Case 20 of 2012", 
    "datedelivered": "2015-10-22T21:00:00.000Z", 
    "judge": "George Matatia Abaleka Dulu", 
    "court": "High Court", 
    "location": "Garissa", 
    "accused": "Abdi Sheikh Mohamed", 
    "judgment": "The accused Abdi Sheikh Mohamed stands charged with the offence of murder contrary to Section 203 as read with Section 204 of the Penal Code. The particulars of the offence are that on 8th May 2012 at Ifo Refugee camp, Lagdera District within Garissa County murdered Othon Ubang Alwal. He has denied the charge." 
}, 
{ 
    "id": 2, 
    "casenumber": "Criminal Case 21 of 2012", 
    "datedelivered": "2015-11-22T21:00:00.000Z", 
    "judge": "Lilo", 
    "court": "High Court", 
    "location": "Nairobi", 
    "accused": "Stitch", 
    "prosecution": "Milo", 
    "judgment": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum" 
} 
] 
0

Как указано выше @CodingPickle, необходимо лишить недействительный JSON первого:

data := `{"result":[ 
{ 
    "id": 1, 
    ... 
}, 
{ 
    "id": 2, 
    ... 
}]}` 

Как хорошо, вам необходимо добавить JSon defn, чтобы в структуры:

type Result struct { 
    Result []Case `json:"result"` 
} 

type Case struct { 
    ID   int `json:"id"` 
    CaseNumber string `json:"casenumber"` 
    DateDelivered string `json:"datedelivered"` 
    Judge   string `json:"judge"` 
    Court   string `json:"court"` 
    Location  string `json:"location"` 
    Accused  string `json:"accused"` 
    Prosecution string `json:"prosecution"` 
    Judgment  string `json:"judgement"` 
} 

Пример:

http://play.golang.org/p/KUbDpSxMVI

Смежные вопросы