How to create hierarchical json structure by slice string path - json

I'm building a backend for a file manager written in Go.
I'm looking for a way to make an example slice string path.
sliceStr := []string{
"/file_A.txt",
"/folder_B/file_B.txt",
"/folder_C/sub_folder_C/file_C.txt",
"/folder_C/sub_folder_C/file_C_2.txt",
}
to create an api that returns a hierarchical json structure to pass to the frontend using Devextreme FileManager. Like below
[
{
"name": "file_A.txt",
"isDirectory": false
},
{
"name": "folder_B",
"isDirectory": true,
"items": [
{
"name": "file_B.txt",
"isDirectory": false
}
]
},
{
"name": "folder_C",
"isDirectory": true,
"items": [
{
"name": "sub_folder_C",
"isDirectory": true,
"items": [
{
"name": "file_C.txt",
"isDirectory": false,
},
{
"name": "file_C_2.txt",
"isDirectory": false
}
]
}
]
}
]

you can try this method
join the slice into a byte array
Implement you own json UnmarshalJSON
type Yourstruct struct {
.......
}
func (t *Yourstruct ) UnmarshalJSON(data []byte) error
demo case

Related

RealmList<String> as a JSON Schema - Mongo DB Realm

I have a simple model class from which I need to generate the schema on Mongo DB Atlas. But I'm having troubles when it comes to defining RealmList<String> inside a JSON schema. If I insert "array" as a bsonType, I get an error. What should I write instead?
Model class:
class Note : RealmObject {
#PrimaryKey
var _id: ObjectId = ObjectId.create()
var title: String = ""
var description: String = ""
var images: RealmList<String> = realmListOf()
var date: RealmInstant = RealmInstant.from(System.currentTimeMillis(),0)
}
Current Schema:
{
"bsonType": "object",
"properties": {
"_id": {
"bsonType": "objectId"
},
"title": {
"bsonType": "string"
},
"description": {
"bsonType": "string"
},
"images": {
"bsonType": "array"
},
"date": {
"bsonType": "date"
}
},
"required": [
"_id",
"title",
"description",
"images",
"date"
],
"title": "Note"
}
I am not sure which mode you're using but if you're in development mode, when you add an object in the SDK, the server will automatically generate a matching object, as long as the changes are additive, like adding a new object or property
In the queston, the 'images' bson definition looks incomplete
"images": {
"bsonType": "array"
},
While it is an array, it's an array of strings so I believe it should look more like this
"images": {
"bsonType": "array",
"items": {
"bsonType": "string"
}
}
Where the type of items is defined as a string

Manipulating mongodb's bson.D output format

Im using FindOne to query one row of data (single document):
package main
import (
"context"
"fmt"
"github.com/fatih/color"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func mongoDbFindOne(key, value string) bson.D {
var result bson.D
_ = Collection.FindOne(context.TODO(), bson.D{{key, value}}).Decode(&result)
color.Green("[+] Found: %+v\n", result)
return result
}
And this a small part of how the result is shown:
[
{
"Key": "_id",
"Value": "1600540844649"
},
{
"Key": "hostname",
"Value": "DESKTOP-xxxxxx"
},
{
"Key": "cmdLine",
"Value": []
},
{
"Key": "pid",
"Value": 4816
}
]
But this how i want it to be:
[
{
"_id": "1600540844649"
},
{
"hostname": "DESKTOP-xxxxxx"
},
{
"cmdLine": []
},
{
"pid": 4816
}
]
Or:
[
{
"_id": "1600540844649",
"hostname": "DESKTOP-xxxxxx",
"cmdLine": [],
"pid": 4816,
}
]
What should i do? I have searched through SO and google but no luck. Should i use struct or creating any objects? I also searched for saving/converting bson to json but there is solution to it.
I found the solution myself:
Using bson.M instead of bson.D solved my issue:
import (
"context"
"fmt"
"github.com/fatih/color"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func mongoDbFindOne(key, value string) bson.M {
var result bson.M
_ = Collection.FindOne(context.TODO(), bson.M{key:value}).Decode(&result)
color.Green("[+] Found: %+v\n", result)
return result
}

How do I get a configurationSection as string?

I am working with .NETCore 2.0 I want to load a complete configuration-section as string.
To be specific, I want to do Json-Schema validation and my schema is stored in appsettings.json:
{
...
"schemas": {
"project": {
"title": "Project",
"type": "object",
"required": [ "param1" ],
"additionalProperties": false,
"properties": {
"param1": {
"type": "string"
},
"param2": {
...
}
}
}
},
...
}
Now I want to load configuration-section "schemas.project" as string and let Json.NET Schema do the schema parsing.
Something like this:
var schemaString = this.configuration.GetSection("schemas.project").Get<string>();
var schema = JSchema.Parse(schemaString);
...
Is there a way to load a complete configuration-section as string? Otherwise I'll read in the schema-file as string..

Using JSON API Serializer to create more complicated JSON

The examples here don't go nearly far enough in explaining how to produce a more complicated structure...
If I want to end up with something like:
{
"data": {
"type": "mobile_screens",
"id": "1",
"attributes": {
"title": "Watch"
},
"relationships": {
"mobile_screen_components": {
"data": [
{
"id": "1_1",
"type": "mobile_screen_components"
},
{
"id": "1_2",
"type": "mobile_screen_components"
},
...
]
}
}
},
"included": [
{
"id": "1_1",
"type": "mobile_screen_components",
"attributes": {
"title": "Featured Playlist",
"display_type": "shelf"
},
"relationships": {
"playlist": {
"data": {
"id": "938973798001",
"type": "playlists"
}
}
}
},
{
"id": "938973798001",
"type": "playlists",
"relationships": {
"videos": {
"data": [
{
"id": "5536725488001",
"type": "videos"
},
{
"id": "5535943875001",
"type": "videos"
}
]
}
}
},
{
"id": "5536725488001",
"type": "videos",
"attributes": {
"duration": 78321,
"live_stream": false,
"thumbnail": {
"width": 1280,
"url":
"http://xxx.jpg?pubId=694940094001",
"height": 720
},
"last_published_date": "2017-08-09T18:26:04.899Z",
"streams": [
{
"url":
"http://xxx.m3u8",
"mime_type": "MP4"
}
],
"last_modified_date": "2017-08-09T18:26:27.621Z",
"description": "xxx",
"fn__media_tags": [
"weather",
"personality"
],
"created_date": "2017-08-09T18:23:16.830Z",
"title": "NOAA predicts most active hurricane season since 2010",
"fn__tve_authentication_required": false
}
},
...,
]
}
what is the most simple data structure and serializer I can set up?
I get stumped after something like:
const mobile_screen_components = responses.map((currentValue, index) => {
id[`id_${index}`];
});
const dataSet = {
id: 1,
title: 'Watch',
mobile_screen_components,
};
const ScreenSerializer = new JSONAPISerializer('mobile_screens', {
attributes: ['title', 'mobile_screen_components'],
mobile_screen_components: {
ref: 'id',
}
});
Which only gives me:
{
"data": {
"type": "mobile_screens",
"id": "1",
"attributes": { "title": "Watch" },
"relationships": {
"mobile-screen-components": {
"data": [
{ "type": "mobile_screen_components", "id": "1_0" },
{ "type": "mobile_screen_components", "id": "1_1" },
{ "type": "mobile_screen_components", "id": "1_2" },
{ "type": "mobile_screen_components", "id": "1_3" },
{ "type": "mobile_screen_components", "id": "1_4" },
{ "type": "mobile_screen_components", "id": "1_5" }
]
}
}
}
}
I have no idea how to get the "included" sibling to "data." etc.
So, the question is:
what is the most simple data structure and serializer I can set up?
Below is the simplest object that can be converted to JSON similar to JSON in the question using jsonapi-serializer:
let dataSet = {
id: '1',
title: 'Watch',
mobile_screen_components: [
{
id: '1_1',
title: 'Featured Playlists',
display_type: 'shelf',
playlists: {
id: 938973798001,
videos: [
{
id: 5536725488001,
duration: 78321,
live_stream: false
},
{
id: 5535943875001,
duration: 52621,
live_stream: true
}
]
}
}
]
};
To serialize this object to JSON API, I used the following code:
let json = new JSONAPISerializer('mobile_screen', {
attributes: ['id', 'title', 'mobile_screen_components'],
mobile_screen_components: {
ref: 'id',
attributes: ['id', 'title', 'display_type', 'playlists'],
playlists: {
ref: 'id',
attributes: ['id', 'videos'],
videos: {
ref: 'id',
attributes: ['id', 'duration', 'live_stream']
}
}
}
}).serialize(dataSet);
console.log(JSON.stringify(json, null, 2));
The first parameter of JSONAPISerializer constructor is the resource type.
The second parameter is the serialization options.
Each level of the options equals to the level of the nested object in serialized object.
ref - if present, it's considered as a relationships.
attributes - an array of attributes to show.
Introduction
First of all we have to understand the JSON API document data structure
[0.1] Refering to the top level (object root keys) :
A document MUST contain at least one of the following top-level
members:
data: the document’s “primary data”
errors: an array of error objects
meta: a meta object that contains non-standard meta-information.
A document MAY contain any of these top-level members:
jsonapi: an object describing the server’s implementation
links: a links object related to the primary data.
included: an array of resource objects that are related to the primary data and/or each other (“included resources”).
[0.2]
The document’s “primary data” is a representation of the resource or
collection of resources targeted by a request.
Primary data MUST be either:
a single resource identifier object, or
null, for requests that target single resources
an array of resource identifier
objects, or an empty array ([]), for reqs. that target
collections
Example
The following primary data is a single resource object:
{
"data": {
"type": "articles",
"id": "1",
"attributes": {
// ... this article's attributes
},
"relationships": {
// ... this article's relationships
}
}
}
In the (jsonapi-serializer) documentation : Available serialization option (opts argument)
So in order to add the included (top-level member) I performed the following test :
var JsonApiSerializer = require('jsonapi-serializer').Serializer;
const DATASET = {
id:23,title:'Lifestyle',slug:'lifestyle',
subcategories: [
{description:'Practices for becoming 31337.',id:1337,title:'Elite'},
{description:'Practices for health.',id:69,title:'Vitality'}
]
}
const TEMPLATE = {
topLevelLinks:{self:'http://example.com'},
dataLinks:{self:function(collection){return 'http://example.com/'+collection.id}},
attributes:['title','slug','subcategories'],
subcategories:{ref:'id',attributes:['id','title','description']}
}
let SERIALIZER = new JsonApiSerializer('pratices', DATASET, TEMPLATE)
console.log(SERIALIZER)
With the following output :
{ links: { self: 'http://example.com' },
included:
[ { type: 'subcategories', id: '1337', attributes: [Object] },
{ type: 'subcategories', id: '69', attributes: [Object] } ],
data:
{ type: 'pratices',
id: '23',
links: { self: 'http://example.com/23' },
attributes: { title: 'Lifestyle', slug: 'lifestyle' },
relationships: { subcategories: [Object] } } }
As you may observe, the included is correctly populated.
NOTE : If you need more help with your dataSet, edit your question with the original data.

Go structure for unmarshalling a JSON array

So I have some JSON (courtesy of the PetFinder API) that has a JSON array "pet". I want to unmarshal from it, using the "encoding/json" package, a slice of pet structs. What would this kind of structure look like? I can't find any examples of how the unmarshall function handles JSON arrays.
Here's what I was planning to do once I had a proper struct:
pfetch := new(PetsFetcher) // where PetsFetcher is the struct im asking for
err := json.Unmarshal(body, &pfetch)
And here's the json that is in body (in the form of a slice of ascii bytes):
{
"petfinder": {
"lastOffset": {
"$t": 5
},
"pets": {
"pet": [
{
"options": {
"option": [
{
"$t": "altered"
},
{
"$t": "hasShots"
},
{
"$t": "housebroken"
}
]
},
"breeds": {
"breed": {
"$t": "Dachshund"
}
}
},
{
"options": {
"option": {
"$t": "hasShots"
}
},
"breeds": {
"breed": {
"$t": "American Staffordshire Terrier"
}
},
"shelterPetId": {
"$t": "13-0164"
},
"status": {
"$t": "A"
},
"name": {
"$t": "HAUS"
}
}
]
}
}
}
Thanks in advance.
I really have no idea what those $t attributes are doing there in your JSON, so let’s answer your question with a simple example. To unmarshal this JSON:
{
"name": "something",
"options": [
{
"key": "a",
"value": "b"
},
{
"key": "c",
"value": "d"
},
{
"key": "e",
"value": "f"
},
]
}
You need this Data type in Go:
type Option struct {
Key string
Value string
}
type Data struct {
Name string
Options []Option
}
You can unmarshal a javascript array into a slice. The marhsal/unmarshalling rules are described under Marshal in the json package.
To unmarshal keys that look like "$t", you'll have to annotate the struct that it'll unpack into.
For example:
type Option struct {
Property string `json:"$t,omitempty"`
}
It may be that the $t that appear are a mistake, and are supposed to be keys in a dictionary.