Convert JSON results with variable field names and value types

Convert JSON results with variable field names and value types

Content Index :

Convert JSON results with variable field names and value types
Tag : json , By : Vijayant Singh
Date : November 29 2020, 04:01 AM

wish helps you Since your parameter names can be anything, I would suggest using a Dictionary(Of String, String) for that part. Declare your model classes like this:
Class RootObject
    Public Property Data As List(Of Item)
End Class

Class Item
    Public Property ID As String
    Public Property Name As String
    Public Property ObjCode As String
    Public Property ParameterValues As Dictionary(Of String, String)
End Class
Dim root As RootObject = JsonConvert.DeserializeObject(Of RootObject)(json)
For Each item In root.Data
    Console.WriteLine("ID: " & item.ID)
    Console.WriteLine("Name: " & item.Name)
    Console.WriteLine("ObjCode: " & item.ObjCode)

    Console.WriteLine(String.Format("{0,-45} {1}", "Parameter Name", "Parameter Value"))
    Console.WriteLine(New String("-", 45) & " " & New String("-", 20))

    For Each kvp In item.ParameterValues
        Console.WriteLine(String.Format("{0,-45} {1}", kvp.Key, kvp.Value))
If kvp.Value Is GetType(JArray) Then
    Dim list As List(Of String) = DirectCast(kvp.Value, JArray).ToObject(Of List(Of String))
    ... handle multiple values ...
    Dim str As String = DirectCast(kvp.Value, String)
    ... handle single value ...
End If
Public Class SingleOrArrayDictionaryConverter(Of T)
    Inherits JsonConverter

    Public Overrides Function CanConvert(objectType As Type) As Boolean
        Return objectType = GetType(Dictionary(Of String, List(Of T)))
    End Function

    Public Overrides Function ReadJson(reader As JsonReader, objectType As Type, existingValue As Object, serializer As JsonSerializer) As Object
        Dim obj = JObject.Load(reader)
        Dim dict = New Dictionary(Of String, List(Of T))
        For Each prop In obj.Properties()
            If prop.Value.Type = JTokenType.Array Then
                dict.Add(prop.Name, prop.Value.ToObject(Of List(Of T)))
                dict.Add(prop.Name, New List(Of T) From {prop.Value.ToObject(Of T)})
            End If
        Return dict
    End Function

    Public Overrides ReadOnly Property CanWrite As Boolean
            Return False
        End Get
    End Property

    Public Overrides Sub WriteJson(writer As JsonWriter, value As Object, serializer As JsonSerializer)
        Throw New NotImplementedException()
    End Sub
End Class
    <JsonConverter(GetType(SingleOrArrayDictionaryConverter(Of String)))>
    Public Property ParameterValues As Dictionary(Of String, List(Of String))

No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

convert variable types when creating dataframe from cor.test results

Tag : r , By : nobodyzzz
Date : March 29 2020, 07:55 AM
may help you . This is how I'd do it. If you do everything "right", the output is already in numeric so no coercion is necessary (if not, you would use as.numeric(object$variable)). When I create the inter variable, I insert the desired components so that I can construct lower/upper CI variables. Notice, that test is now a "proper" data.frame that can be easier to work with (you can easily extract any item you want).
# split data frame according the the individual IDs
individual.list <- split(WW_Wing_SI, WW_Wing_SI$Individual_ID)

# apply cor.test() with extract to each element of the list
inter <- sapply(individual.list, function(temp) {
            a <- cor.test(temp$Delta13C, temp$FeatherPosition,
                    method="pearson")[c("estimate", "p.value", "conf.int")]
            out <- data.frame(cor = a$estimate, p.value = a$p.value, lowerCI = a$conf.int[1], upperCI = a$conf.int[2])
        }, simplify = FALSE)
test <- do.call("rbind", inter)

                  cor    p.value    lowerCI    upperCI
WW_08A_02 -0.76706752 0.01585509 -0.9481677 -0.2098478
WW_08A_03 -0.02320767 0.95274294 -0.6768966  0.6509469

JSON results into a variable and store in hidden input field

Tag : json , By : Shitic
Date : March 29 2020, 07:55 AM
this one helps. I wrote code below that is working perfectly for displaying the results of my sales tax calculation into a span tag. But, I am not understanding how to change the "total" value into a variable that I can work with. , If you are using a hidden field inside a form, you could do:
//inside $.post -> success handler.
$('input[name=yourHiddenFieldName]', yourForm).val(data.total);
var dataValue = $('input[name=yourHiddenFieldName]', yourForm).val();

Golang convert json with variable types to strings

Tag : json , By : shenol
Date : March 29 2020, 07:55 AM
wish of those help For this answer I'm assuming that JSON in your example is an example of (part of) your JSON input. In this case, your JSON has a specific structure: you know which attributes are coming with a known data type and also you know which attributes a dynamic. For example, you could unmarshal your JSON into smth like ResponseObj below:
package main

import (

type ResponseObj struct {
    Response []Item `json:"response"`

type Item struct {
    TInt   int         `json:"t_int"`
    TBool  bool        `json:"t_bool"`
    TMixed interface{} `json:"t_null_or_string"`

func main() {

    json_byte := []byte(`{"response":[{"t_int":1, "t_bool": true,  "t_null_or_string": null}, {"t_int":2, "t_bool": false, "t_null_or_string": "string1"}]}`)

    data_json := ResponseObj{}
    if err := json.Unmarshal(json_byte, &data_json); err != nil {
    fmt.Printf("%+v\n", data_json)

How to Pre Process Json String in Java :: Convert Capitalised Field names to lowerCase Camel case names

Tag : java , By : user179863
Date : March 29 2020, 07:55 AM
I hope this helps . I think you should really consider letting your JSON deserializer handle this, but if this really isn't a possibility you can always use good old string manipulation :
String input; // your JSON input
Pattern p = Pattern.compile("\"([A-Z])([^\"]*\"\\s*:)"); // matches '"Xxxx" :'
Matcher m = p.matcher(input);
StringBuffer output = new StringBuffer();
while (m.find()) {
   m.appendReplacement(output, String.format("\"%s$2", m.group(1).toLowerCase());

How do I convert JSON with variable variable names into swift object?

Tag : ios , By : user158220
Date : March 29 2020, 07:55 AM
help you fix your problem As mentioned you can decode this as a dictionary, first define a struct for the data you want to decode
struct ReportData: Decodable {
    let at: SomeData
    let firstUTC: Date
    let hws: SomeData
let decodedData = try self.decoder.decode([String:ReportData].self, from: data)
if let keys = decodedData ["sol_keys"] {
    for key in keys {
        let report = decodeData[key]
Related Posts Related QUESTIONS :
  • How to send Map as String in POST request in flutter?
  • Difficulty fetching json data from API using Angular
  • Reading JSON data for my select query in SQL Server
  • AWS CloudFormation Template (JSON) to Create EC2 - Unexpected Error
  • How to concat multiple fields to same line with jq
  • Issue sending POST request from Swift
  • Storing JSON in BigQuery
  • How to get the value of a key in a JSON?
  • How to validate JSON input in Go
  • Extracting specific and latest data from http webserver using golang
  • Incorrect type. Expected "object"
  • json_to_record with embedded encoded json in PostgreSQL >= 10
  • Nested json extract from powershell
  • Parsing Json using Golang
  • Type 'number' is not assignable to type 'string'. How to cast number to string
  • kubectl - format the resource quota values in json format
  • Initializing and inserting nested JSON data in Golang?
  • Open JSON files in PhpStorm built-in web server
  • Extract Badge ID from JSON in .gitlab-ci.yml
  • Sharing Json Schema files among projects with versioning
  • Export Json data to an excel file using Angular 4
  • Return an empty array instead of null with golang for json return with gin
  • can Kafka connect value conveter (JSONConverter) can be used to convert GPB?
  • read json and access multiple keys
  • Spark How to get number of Keys changed in two JSONS in Scala?
  • Break JSON in pager "less"
  • How to filter Map in Flutter?
  • Convert hashmap to simple object in Groovy
  • Not extracting json properly using json4s
  • How do I display JSON data in my tableView when objects have the same value?
  • Where I can parse IoT data in Azure so I can afterwards save it to SQL DB
  • How to unmarshal this json string
  • What's wrong with my JSON?
  • JSON parsing problem in BlackBerry
  • GWT: How can I use JsonpRequestBuilder to handle a Json response of a list
  • JSON feed to Java Object
  • json character encoding problem
  • JSON Loading Speed Optimization: Use online API vs. create my own API based on that?
  • How can I access some JSON documents from my AWS lambda function?
  • How to extract multiple correlating variables from a JSon
  • Schema/Resolve for nested objects graphql/mongoose
  • Dynamics 365 opportunity EntityType processid and stagename error
  • How to convert dataframe output to json format and then Normalize the data?
  • In Angular, how do I avoid a "Property 'json' does not exist on type 'Object'" error?
  • Python giving vague error when trying to parse JSON object
  • Invalid JSON literal: xxx when calling ASMX service from Angular8
  • How to write the data converted from json to csv without skipping the rows
  • Unpacking JSON Into Flat Format
  • TypeError: items is undefined while reading a json using fetch in reactjs
  • How to insert date to the web path api
  • schema validation get value from sum of another value of json
  • Deleting a field in nested objects in JQ
  • Get multiple JSON keypair values within a JSON object only if a specific keypair value matches iterable
  • parse contents from returned json to el-dropdown-item
  • Replace content by key in JSON
  • JSON parsing using String Condition with JMESPATH
  • Only Output Rule Alerts to Suricata EVE
  • How to unmarshal a json string with a hyphen in key to a struct?
  • How can I aggregate sub-values into arrays with jq?
  • How to parse JSON array in Flutter with length of one?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com