且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将计算出的密钥添加到集合中

更新时间:2023-11-30 23:42:28

创建JSON的修改版本是F#数据类型提供程序特别困难的一件事.使得这一点变得如此困难的事实是,我们可以从源JSON推断类型,但是我们无法预测"人们可能想要添加的字段类型.

Creating modified versions of the JSON is sadly one thing that the F# Data type provider does not make particularly easy. What makes that hard is the fact that we can infer the type from the source JSON, but we cannot "predict" what kind of fields people might want to add.

为此,您需要访问JSON值的基础表示形式并对其进行操作.例如:

To do this, you'll need to access the underlying representation of the JSON value and operate on that. For example:

type ls = JsonProvider<"""
  [{"sex":"male","height":180,"weight":85},
   {"sex":"male","height":160,"weight":60},
   {"sex":"male","height":180,"weight":85}]""">

let dt = ls.GetSamples()

let newJson = 
  dt
  |> Array.map (fun recd ->
      // To do the calculation, you can access the fields via inferred types 
      let bmi = float recd.Height / float recd.Weight

      // But now we need to look at the underlying value, check that it is
      // a record and extract the properties, which is an array of key-value pairs
      match recd.JsonValue with
      | JsonValue.Record props ->
          // Append the new property to the existing properties & re-create record
          Array.append [| "bmi", JsonValue.Float bmi |] props
          |> JsonValue.Record
      | _ -> failwith "Unexpected format" )

// Re-create a new JSON array and format it as JSON
JsonValue.Array(newJson).ToString()