v icon indicating copy to clipboard operation
v copied to clipboard

Encode/decode embedded struct as fields of parent struct in JSON

Open ArtemkaKun opened this issue 2 years ago • 0 comments

Describe the feature

I think embedded structs should be encoded/decoded as fields of parent struct, not as a separate inner object, in JSON. This will help to implement DRY code.

Use Case

struct NodeLocation {
	LocationData
	file          string
	line          int
}

struct Range {
	begin LocationData
	end  LocationData
}

struct LocationData {
	offset        int
	column        int		 [json: 'col']
	token_length int		 [json: 'tokLen']
	source_file   SourceFile [json: 'includedFrom']
	spelling_file SourceFile [json: 'spellingLoc']
}

instead of

struct NodeLocation {
	offset        int
	file          string
	line          int
	column        int		 [json: 'col']
	token_length int		 [json: 'tokLen']
	source_file   SourceFile [json: 'includedFrom']
	spelling_file SourceFile [json: 'spellingLoc']
}

struct Range {
	begin LocationData
	end  LocationData
}

struct LocationData {
	offset        int
	column        int		 [json: 'col']
	token_length int		 [json: 'tokLen']
	source_file   SourceFile [json: 'includedFrom']
	spelling_file SourceFile [json: 'spellingLoc']
}

Proposed Solution

No response

Other Information

Code

module main

import json

struct TestA {
    TestB
}

struct TestB {
    number int
}

fn main() {
    a := TestA{
        TestB{
            number: 1
        }
    }

    println(json.encode(a))
}

Expected

{"number":1}

Got

{"TestB":{"number":1}}

Acknowledgements

  • [ ] I may be able to implement this feature request
  • [ ] This feature might incur a breaking change

Version used

V 0.3.3

Environment details (OS name and version, etc.)

OS: linux, "Garuda Linux"
Processor: 16 cpus, 64bit, little endian, AMD Ryzen 7 3800X 8-Core Processor
CC version: cc (GCC) 12.2.1 20230201

getwd: /home/yuart/Projects/c2v
vmodules: /home/yuart/.vmodules
vroot: /usr/lib/vlang
vexe: /usr/lib/vlang/v
vexe mtime: 2023-02-10 13:19:23
is vroot writable: false
is vmodules writable: true
V full version: V 0.3.3 d1f57ea

ArtemkaKun avatar Feb 19 '23 11:02 ArtemkaKun