質問

Given the code:

#if INTERACTIVE
#r "bin\Debug\FSharp.Data.dll"

#endif

open System
open FSharp.Data
open FSharp.Data.Json

let testJson = """{ "workingDir":"hello", "exportDir":"hi there", "items":[{ "source":"", "dest":"", "args": {"name":"that"} }] }"""

//here is where i get the error
let Schema = JsonProvider<testJson>

The last line keeps giving me the error "This is not a constant expression or valid custom attribute value"-- what does that mean? How can i get it to read this JSON?

役に立ちましたか?

解決

The string has to be marked as a constant. To do that, use the [<Literal>] attribute. Also, the type provider creates a type, not a value, so you need to use type instead of let:

open FSharp.Data

[<Literal>]
let testJson = """{ "workingDir":"hello", "exportDir":"hi there", "items":[{ "source":"", "dest":"", "args": {"name":"that"} }] }"""

type Schema = JsonProvider<testJson>

他のヒント

The JsonProvider can be viewed as a parametrized JSON parser (plus the data type that the parser produces) that is specialized at compile time.

The parameter you give to it (a string or a path to JSON file) defines the structure of JSON data -- a schema if you wish. This allows the provider to create a type that will have all the properties your JSON data should have, statically, and the set of those properties (along with their respective types) are defined (actually inferred from) with the JSON sample that you give to the provider.

So the correct way to use the JsonProvider is shown in one of the examples from the documentation:

// generate the type with a static Parse method with help of the type provider
type Simple = JsonProvider<""" { "name":"John", "age":94 } """>
// call the Parse method to parse a string and create an instance of your data
let simple = Simple.Parse(""" { "name":"Tomas", "age":4 } """)
simple.Age
simple.Name

The example was taken from here.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top