Reputation: 877
giving a json
{ "id": 1, "name": "one" }
I would like to produce two strings:
one with keys like:
"id", "name"
and one with values
1, "one"
Seems trivial, but so far I don't even know where to start. Should I parse it with some JSON parser to a JSONValue and then get the keys? Is it tangible giving the dynamic nature of the JSON which can be given? Or simply take a REGEX route? Any other ideas?
Upvotes: 2
Views: 193
Reputation: 13577
If you want to parse JSON on .NET, there's really one go-to solution in town - Newtonsoft JSON.NET.
I assume you want to parse JSON documents where you don't know the schema beforehand. JSON.NET has an object model that can be used to represent a document in memory, and you can inspect that to produce the output you want.
Here's a sample that should get you going:
open Newtonsoft.Json
open Newtonsoft.Json.Linq
let json = "{ \"id\": 1, \"name\": \"one\" }"
let rep = JObject.Parse(json)
let names, values =
[ for p in rep.Properties() do
yield p.Name, p.Value.ToObject<string>() ]
|> List.unzip
Obviously the sample only handles flat documents, but it should be fairly simple to make it recursive.
If you do know the schema, you can use a type provider or use JSON.NET to deserialize a JSON document straight into a record type.
Upvotes: 5