我有json文件test.json
{"response":[
{
"aid":209228783,
"thumb_id":"348954492",
"owner_id":-79421906,
"title":"title1",
"description":"description1",
"created":"1420821911",
"updated":"1421783832",
"size":284,
"can_upload":1
},
{
"aid":205134660,
"thumb_id":"353880937",
"owner_id":-79421906,
"title":"title2",
"description":"description2",
"created":"1415386976",
"updated":"1425057394",
"size":308,
"can_upload":0
},
{
"aid":204502901,
"thumb_id":"347548800",
"owner_id":-79421906,
"title":"title3",
"description":"description3",
"created":"1414438611",
"updated":"1419706388",
"size":1030,
"can_upload":0
}
]}
示例,需要从json文件值获取" help"," description"和"尺寸"。 我创建了新的类型响应
type response = {
aid: int;
thumb_id: string;
owner_id: int;
title: string;
description: string;
created: string;
updated: string;
size: int;
can_upload: int
}
我如何使用它是我的json请求中的类型
let des json =
[json]
|> filter_member "response"
|> flatten
|> to_list;;
let json = Yojson.Basic.from_file "test.json" in
List.iter (fun y -> print_endline(y.aid^"--->"^y.title)) (des json);;
此代码返回错误类型错误。
答案 0 :(得分:3)
(让您的回复记录稍微小一点,但仍然可以得到重点)
type response = {descr:string;
size: int;
can_upload: int}
let record_list =
let open Yojson.Basic.Util in
let f = Yojson.Basic.from_file "test.json" in
List.fold_right
(fun item r_list ->
{descr = member "description" item |> to_string;
size = member "size" item |> to_int;
can_upload = member "can_upload" item |> to_int} :: r_list)
(member "response" f |> to_list)
[]
答案 1 :(得分:0)
Yojson实际上只是atdgen的运行时。将类型定义放入.atd
文件中,atdgen将使用yojson为您生成样板代码:
(* This is file api.atd *) type response_item = { aid: int; thumb_id: string; owner_id: int; title: string; description: string; created: string; updated: string; size: int; can_upload: int } type response = { response: response_item list; }
Atdgen生成文件api_t.mli
,api_t.ml
,api_j.mli
和api_j.ml
,其中_t
代表类型,_j
代表JSON。请参阅有关如何将atdgen与构建系统集成的教程。
然后,从您的OCaml代码中,您所要做的就是:
let record_list = Ag_util.Json.from_file Api_j.read_response "test.json"