Is the a way to view all of the metadata in the current note?

I’m relatively new to Obsidian and couldn’t find an answer to this in the forums (probably didn’t know what to search).

Is there any way to view all of the metadata (frontmatter values and dataview values) in the current page, preferably in the side bar or top area in view mode, including inline dataview values added using the dataview plugin, e.g. (meta:: value)?

I found this: `$=dv.span(dv.current())` here.
I’m guessing there’s a js way to filter it and add it to the sidebar somehow?
Or maybe a “cleaner” way?
(I probably should add that I don’t speak js)

1 Like

you could create a custom note and pin it to the sidebar.
In that custom note you could add some dataviewjs code to grab the active note and display the metadata of that note.
If you want to have it nice you would need to process that data.
could be a nice addition to dataview as itself I guess (open a suggestion on github)

btw: to get the active note you can do let activeFile = app.workspace.getActiveFile();

so the code could look like

let activeFile = app.workspace.getActiveFile();
dv.span(dv.page(activeFile.basename));
2 Likes

and it doesn’t work… looks like getActiveFile is only picking up the note where it is running in not the note you are viewing / editing.

yes, you need to edit something in the active file to the query refresh the output

if you want a specific place to see the metadata in current note, once the solution in the side pane is a little tricky (and doen’t refresh as wanted) you can use a folding callout (or not) as this:

> [!info]-
> `$=dv.span(dv.current())`
2 Likes

Thank you for the directions @mbreiden and @mnvwvnm.

The foldable callout is a fair solution, even though it requires entering the code manually in every page (won’t work with transclusions I guess?). I’ll play around with coding from a separate note in the sidebar when/if I know some more js.

Is there any way to filter the list resulting from `$=dv.span(dv.current())`? at least removing the first “file” item from it (sorry if this is trivial).

Two things:
1 - as @mbreiden said you can use a dataviewjs query in a separate note fixed in sidebar. And the code is something like this:

```dataviewjs
const ws = app.workspace.lastActiveFile;
dv.span(dv.page(ws.basename))
```

But the point is: it only refresh to the real active file in the workspace if you edit something in the current file. I don’t know why, but this is the current behavior.

2 - about the «removing the “file” item», I don’t understand well your goal. you see the file level and inside all the implicit fields; if you have any custom fields (as key:: value), then this metadata is outside the “file” level (they’re at the same level, not nested in “file”).
But if you want only fields inside “file” level, then use

`$=dv.span(dv.current().file)`
2 Likes

Thank you @mnvwvnm ,
Finally got the pinned note on the sidebar to work (indeed, refreshing only on edit of the active note).

Sorry, I was unclear… I would like the opposite of what you suggested, that is, everything other than the “file” item information (as a quick solution to my current situation).
And even better, the ability to filter manually (once I understand your code myself), if in the future I would like to create more focused such view of my metadata.

Really appreciate your help :slight_smile:

Topic

Summary
  • How to get each key/value of the metadata(YAML and DVIF) in one page? (DVJS10)
  • How to get each key/value of the metadata(YAML and DVIF) excluding the file key and the duplicated DVIF in one page? (DVJS12)
  • How to get each key/value of the metadata(ONLY the file key) excluding YAML and DVIF in one page? (DVJS20)
  • How to get each key/value of the metadata(ONLY the file key and aWhiteList keys) excluding YAML and DVIF in one page? (DVJS22)

Test

Summary
  • dataview: v0.5.46

input

Summary

the main DVJS file

  • filename : 20221011_Metadata_DVJS


### DVJS12_get_keys_values_excluding_file_key_and_duplicated_DVIF_and_TABLE
// #####################################################################
// The following note is the content of the main DVJS12.



### DVJS22_get_keys_values_of_only_file_key_and_aWhiteList_keys_and_TABLE
// #####################################################################
// The following note is the content of the main DVJS22.




dictionary files:

  • Location: “999_Test/Q87_test_data”

folder: 03

  • filename : dic_19880301
---
Date: 1988-03-01
drinks_y: "[[Black Coffee]]"
---
#Project/P03

drinks_d:: [[Green Tea]] 
exercises_a:: "table tennis", "cycling"
exercises_b:: badminton , walking race
exercises duration:: 90 minutes
expenses:: 100, 200
remark::



DVJS10_get_keys_values_excluding_file_key_and_TABLE

Summary

Main DVJS

Code Name Data type Group By Purposes Remark
DVJS10
_get_keys_values
_excluding_file_key
_and_TABLE
Metadata
of one page
no 1.To gather the key/value of one page
2.To filter the data excluding the file key
3.To display the result as a table

Notes

Summary

The same codes: To get the file.path of the note like [[dic_19880301]]?

  • Suppose that the note like [[dic_19880301]] is unique in your Obsidian vault.
A10: Inline DQL
file_path = `=[[dic_19880301]].file.path`

//=>file_path = 999_Test/Q87_test_data/03/dic_19880301.md

A11: Inline DVJS
file_path = `$=dv.page("dic_19880301").file.path`

//=>file_path = 999_Test/Q87_test_data/03/dic_19880301.md

The same codes: To gather one page like [[dic_19880301]]

M11: Original Example10
// M11. define h_single_page: gather one relevant page
// #####################################################################
let h_single_page = dv
    .pages('"999_Test/Q87_test_data/03/dic_19880301.md"')[0];
//let h_single_page = dv.page("dic_19880301");
//let h_single_page = dv.current();
M11: Another Example11
  • Suppose that the note like [[dic_19880301]] is unique in your Obsidian vault.
// M11. define h_single_page: gather one relevant page
// #####################################################################
// let h_single_page = dv
//     .pages('"999_Test/Q87_test_data/03/dic_19880301.md"')[0];
let h_single_page = dv.page("dic_19880301");
//let h_single_page = dv.current();
M11: Another Example12
  • The code must exist in the note [[dic_19880301]].
// M11. define h_single_page: gather one relevant page
// #####################################################################
// let h_single_page = dv
//     .pages('"999_Test/Q87_test_data/03/dic_19880301.md"')[0];
//let h_single_page = dv.page("dic_19880301");
let h_single_page = dv.current();

code DVJS10_get_keys_values_excluding_file_key_and_TABLE

Summary_code
title: DVJS10_get_keys_values_excluding_file_key_and_TABLE =>1.To gather the key/value of one page 2.To filter the data excluding the `file` key 3.To display the result as a table
collapse: close
icon: 
color: 
```dataviewjs
// M11. define h_single_page: gather one relevant page
// #####################################################################
let h_single_page = dv
    .pages('"999_Test/Q87_test_data/03/dic_19880301.md"')[0];
//let h_single_page = dv.page("dic_19880301");
//let h_single_page = dv.current();


// M21.Gather the key/value of one page : AoA = Array of Arrays
// FILTER_CASE_01: excluding the `file` key
// #####################################################################
let AoA = Object.entries(h_single_page)
    .filter(([key, value]) => key !== "file")
    .map(([key, value]) => [key, value, dv.func.typeof(value)]);


// M31.Output the heading as H3: 
// #####################################################################
dv.span(
    `### M33.Output keys_values of ${h_single_page.file.name}: excluding the file key`
);


// M33.Output AoA:
// #####################################################################
dv.table(["key", "value", "dv.func.typeof"], AoA);




Screenshots(DVJS10):


DVJS12_get_keys_values_excluding_file_key_and_duplicated_DVIF_and_TABLE

Summary

Main DVJS

Code Name Data type Group By Purposes Remark
DVJS12
_get_keys_values
_excluding_file_key
_and_duplicated_DVIF
_and_TABLE
Metadata
of one page
no 1.To gather the key/value of one page
2.To filter the data excluding the file key
3.To filter the data excluding the duplicated DVIF created by Dataview
4.To display the result as a table

code DVJS12_get_keys_values_excluding_file_key_and_duplicated_DVIF_and_TABLE

Summary_code
title: DVJS12_get_keys_values_excluding_file_key_and_duplicated_DVIF_and_TABLE =>1.To gather the key/value of one page 2.To filter the data excluding the `file` key 3.To filter the data excluding the duplicated DVIF created by Dataview 4.To display the result as a table
collapse: close
icon: 
color: 
```dataviewjs
// M11. define h_single_page: gather one relevant page
// #####################################################################
let h_single_page = dv
    .pages('"999_Test/Q87_test_data/03/dic_19880301.md"')[0];
//let h_single_page = dv.page("dic_19880301");
//let h_single_page = dv.current();


// M21. define a_org_keys: gather the original keys of one page
// #####################################################################
let a_org_keys = Object.keys(h_single_page);


// M23. define a_org_keys_to_lower_case: transform a_org_keys into lower case
// #####################################################################
let a_org_keys_to_lower_case = a_org_keys.map((key) => dv.func.lower(key));


// M25. define h_org_keys_to_lower_case: {date: 2}
// calculate the QTY of each lower case key
// #####################################################################
let h_org_keys_to_lower_case = {};
a_org_keys_to_lower_case.forEach((s_lower_key) => {
    if (s_lower_key in h_org_keys_to_lower_case) {
        h_org_keys_to_lower_case[s_lower_key]++;
    } else {
        h_org_keys_to_lower_case[s_lower_key] = 1;
    }
});


// M25.DB01 Debug Output: h_org_keys_to_lower_case
// #####################################################################
//dv.span("The following is the content of the `h_org_keys_to_lower_case`.\n");
//dv.span(JSON.stringify(h_org_keys_to_lower_case, null, 2), "\n");


//The following is the content of the h_org_keys_to_lower_case.
// let h_org_keys_to_lower_case = {
//     file: 1,
//     date: 2,
//     drinks_y: 1,
//     drinks_d: 1,
//     exercises_a: 1,
//     exercises_b: 1,
//     "exercises duration": 1,
//     expenses: 1,
//     remark: 1,
//     "exercises-duration": 1,
// };


// M31.Gather the key/value of one page : AoA = Array of Arrays
// FILTER_CASE_01: excluding the `file` key
// FILTER_CASE_02: excluding the duplicated DVIF created by Dataview:
// #####################################################################
let AoA = Object.entries(h_single_page)
    .filter(([key, value]) => key !== "file")
    .filter(
        ([key, value]) =>
            !h_org_keys_to_lower_case[key] ||
            h_org_keys_to_lower_case[key] === 1
    )
    .map(([key, value]) => [key, value, dv.func.typeof(value)]);


// M51.Output the heading as H3: 
// #####################################################################
dv.span(
    `### M53.Output keys_values of ${h_single_page.file.name}: excluding the file key and the duplicated DVIF`
);


// M53.Output AoA:
// #####################################################################
dv.table(["key", "value", "dv.func.typeof"], AoA);




Screenshots(DVJS12):


DVJS20_get_keys_values_of_only_file_key_and_TABLE

Summary

Main DVJS

Code Name Data type Group By Purposes Remark
DVJS20
_get_keys_values
_of_only_file_key
_and_TABLE
Metadata
of one page
no 1.To gather the key/value of one page h_single_page["file"]
2.To filter the data excluding the frontmatter key
3.To display the result as a table

code DVJS20_get_keys_values_of_only_file_key_and_TABLE

Summary_code
title: DVJS20_get_keys_values_of_only_file_key_and_TABLE =>1.To gather the key/value of one page `h_single_page["file"]` 2.To filter the data excluding the `frontmatter` key 3.To display the result as a table
collapse: close
icon: 
color: 
```dataviewjs
// M11. define h_single_page: gather one relevant page
// #####################################################################
let h_single_page = dv
    .pages('"999_Test/Q87_test_data/03/dic_19880301.md"')[0];
//let h_single_page = dv.page("dic_19880301");
//let h_single_page = dv.current();


// M21.Gather the key/value of one page : AoA = Array of Arrays
// FILTER_CASE_01: excluding the `frontmatter` key
// #####################################################################
let AoA = Object.entries(h_single_page["file"])
    .filter(([key, value]) => key !== "frontmatter")
    .map(([key, value]) => [key, dv.func.typeof(value), value]);


// M31.Output the heading as H3: 
// #####################################################################
dv.span(
    `### M33.Output keys_values of ${h_single_page.file.name}: ONLY the file key excluding the frontmatter key`
);


// M33.Output AoA:
// #####################################################################
dv.table(["key", "typeof", "value"], AoA);




Screenshots(DVJS20):


DVJS22_get_keys_values_of_only_file_key_and_aWhiteList_keys_and_TABLE

Summary

Main DVJS

Code Name Data type Group By Purposes Remark
DVJS22
_get_keys_values
_of_only_file_key
_and_aWhiteList_keys
_and_TABLE
Metadata
of one page
no 1.To gather the key/value of one page h_single_page["file"]
2.To filter the data where aWhiteList icontains key
3.To display the result as a table

Notes

Summary

To modify

Original Example: ONLY the file key and aWhiteList keys
  • (comments)FILTER_CASE_01: Not to exclud the frontmatter key
  • FILTER_CASE_02: To filter the data where aWhiteList icontains key
// M23.Gather the key/value of one page : AoA = Array of Arrays
// (comments)FILTER_CASE_01: excluding the `frontmatter` key
// FILTER_CASE_02: where aWhiteList icontains key
// #####################################################################
let AoA = Object.entries(h_single_page["file"])
    //.filter(([key, value]) => key !== "frontmatter")
    .filter(([key, value]) => dv.func.icontains(aWhiteList, key))
    .map(([key, value]) => [key, dv.func.typeof(value), value]);
Another Example: ONLY the file key
  • (comments)FILTER_CASE_01: Not to exclud the frontmatter key
  • (comments)FILTER_CASE_02: Not to filter the data where aWhiteList icontains key
// M23.Gather the key/value of one page : AoA = Array of Arrays
// (comments)FILTER_CASE_01: excluding the `frontmatter` key
// (comments)FILTER_CASE_02: where aWhiteList icontains key
// #####################################################################
let AoA = Object.entries(h_single_page["file"])
    //.filter(([key, value]) => key !== "frontmatter")
    //.filter(([key, value]) => dv.func.icontains(aWhiteList, key))
    .map(([key, value]) => [key, dv.func.typeof(value), value]);
Another Example: ONLY the file key excluding the frontmatter key
  • FILTER_CASE_01: To exclud the frontmatter key
  • (comments)FILTER_CASE_02: Not to filter the data where aWhiteList icontains key
// M23.Gather the key/value of one page : AoA = Array of Arrays
// (comments)FILTER_CASE_01: excluding the `frontmatter` key
// (comments)FILTER_CASE_02: where aWhiteList icontains key
// #####################################################################
let AoA = Object.entries(h_single_page["file"])
    .filter(([key, value]) => key !== "frontmatter")
    //.filter(([key, value]) => dv.func.icontains(aWhiteList, key))
    .map(([key, value]) => [key, dv.func.typeof(value), value]);

code DVJS22_get_keys_values_of_only_file_key_and_aWhiteList_keys_and_TABLE

Summary_code
title: DVJS22_get_keys_values_of_only_file_key_and_aWhiteList_keys_and_TABLE =>1.To gather the key/value of one page `h_single_page["file"]` 2.To filter the data where aWhiteList icontains key 3.To display the result as a table
collapse: close
icon: 
color: 
```dataviewjs
// M11. define h_single_page: gather one relevant page
// #####################################################################
let h_single_page = dv
    .pages('"999_Test/Q87_test_data/03/dic_19880301.md"')[0];
//let h_single_page = dv.page("dic_19880301");
//let h_single_page = dv.current();


// M21.define aWhiteList : 
// #####################################################################
let aWhiteList = [
    "name",
    "outlinks",
    "inlinks",
    "etags",
    "tags",
    "ctime",
    "mtime",
    "day",
];


// M23.Gather the key/value of one page : AoA = Array of Arrays
// (comments)FILTER_CASE_01: excluding the `frontmatter` key
// FILTER_CASE_02: where aWhiteList icontains key
// #####################################################################
let AoA = Object.entries(h_single_page["file"])
    //.filter(([key, value]) => key !== "frontmatter")
    .filter(([key, value]) => dv.func.icontains(aWhiteList, key))
    .map(([key, value]) => [key, dv.func.typeof(value), value]);


// M31.Output the heading as H3: 
// #####################################################################
dv.span(
    `### M33.Output keys_values of ${h_single_page.file.name}: ONLY the file key and aWhiteList keys`
);


// M33.Output AoA:
// #####################################################################
dv.table(["key", "typeof", "value"], AoA);




Screenshots(DVJS22):


Conclusion

Summary
  • Use the DVJS12 instead of the DVJS10.
  • Use the DVJS22 instead of the DVJS20.

2 Likes

@mbreiden @mnvwvnm @justdoitcc
Thank you so much! that was exactly what I deeded to get going!
Digging in to dv API now with ease thanks to you!
And my OP metadata view is working perfectly (with a slight update on edit hickup :slight_smile:).

@mbreiden @mnvwvnm @justdoitcc since I’m a total beginner with js would appreciate two more shortcuts on these noob questions :blush:

Is there a way for a variable to remain persistent across dataviewjs blocks?

And can I create methods to be reused across the vault?

variable I don’t know.
code yes:
one way would be to use CustomJS
the other dv.view (?) irrc
and you can also use templater javascript feature to include user code.
btw: Create a "Dataview Metadata View" Applet(?) · Issue #1473 · blacksmithgu/obsidian-dataview · GitHub

1 Like

Q1: How to save the state of a variable in order to be able to recreate it when needed?

Summary
  • Q: What is Serializing and Deserializing?
    • A: Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.
  • Q: What Is Serialization?
  • Q: What is serializing and deserializing JSON?
  • Keywords: JSON
  • Key functions: JSON.stringify() and JSON.parse()
  • Keywords: JSON to a file
  • Basic Examples:
    • DVJS11: a JS variable to a JSON string(memory)
    • DVJS13: a JSON string(memory) to a JS variable
  • Basic Examples:
    • DVJS21: a JS variable to a JSON file
    • DVJS23: a JSON file to a JS variable
  • A Very Basic Example:
    • The step M25.DB01 of the DVJS12 :
      • At first: A JavaScript variable is transformed into a JSON string(memory) by the DVJS12.
      • Secondly: It is formatted by “Prettier - Code formatter v9.5.0” and toggled as a comment in the VScode(Visual Studio Code) by myself.
      • At last: It is appended to the note that contains the DVJS12 code by myself.

Summary_M25.DB01 of the DVJS12
```JS
// M25.DB01 Debug Output: h_org_keys_to_lower_case
// #####################################################################
//dv.span("The following is the content of the `h_org_keys_to_lower_case`.\n");
//dv.span(JSON.stringify(h_org_keys_to_lower_case, null, 2), "\n");


//The following is the content of the h_org_keys_to_lower_case.
// let h_org_keys_to_lower_case = {
//     file: 1,
//     date: 2,
//     drinks_y: 1,
//     drinks_d: 1,
//     exercises_a: 1,
//     exercises_b: 1,
//     "exercises duration": 1,
//     expenses: 1,
//     remark: 1,
//     "exercises-duration": 1,
// };
```

Q2: How to reuse user-defined functions, a DVJS, or a DQL?

Summary

1 Like

Topic

Summary
  • How to save the state of a variable in order to be able to recreate it when needed?
    • How to transform a JavaScript variable into a JSON string by using JSON.stringify()? (DVJS11)
    • How to parse a JSON string and transform it into a JavaScript variable by using JSON.parse()? (DVJS13)
    • How to transform a JavaScript variable into a JSON file? (DVJS21)
    • How to transform a JSON file into a JavaScript variable like aoa_drinks? (DVJS23)

Test

Summary
  • dataview: v0.5.46

input

Summary

dictionary files

  • The input data of the DVJS13 is the output data of the DVJS11.
  • The input data of the DVJS23 is the output data of the DVJS21.

DVJS11_transform_a_JavaScript_variable_into_a_JSON_string

Summary

Main DVJS

Code Name Data type Group By Purposes Remark
DVJS11
_transform
_a_JavaScript_variable
_into
_a_JSON_string
1.aoh_drinks:
an array of hashes

2.s_JSON:
a JSON string
no To transform a JavaScript variable into a JSON string by using JSON.stringify() a JS variable to a JSON string(memory)

Notes

Summary

Q1: What does the following DQL statement mean?

// M21. define s_JSON: Transform a JavaScript variable into a JSON string 
// with two space characters as white space for indentation
// JSON.stringify(value[, replacer[, space]])
// #####################################################################
let s_JSON = JSON.stringify(aoh_drinks, null, 2);

A1

  • The above statement means that to transform a JavaScript variable like aoh_drinks into a JSON string like s_JSON by using two space characters as white space for indentation.

code DVJS11_transform_a_JavaScript_variable_into_a_JSON_string

Summary_code
title: DVJS11_transform_a_JavaScript_variable_into_a_JSON_string =>To transform a JavaScript variable into a JSON string by using `JSON.stringify()`
collapse: close
icon: 
color: 
```dataviewjs
// M01. define print() :
// #####################################################################
// version : 2022-05-01 v1.00 Justdoitcc
function print(...aArgs) {
    let aText = [...aArgs];
    let sTextJoined = aText
        .join("")
        .replace(/[ ]/g, "&nbsp")
        .replace(/(\r\n|\r|\n)/g, "<br>");
    dv.el("span", sTextJoined);
    return true;
}


// M11. define aoh_drinks : aoh = an array of hashes
// #####################################################################
// The `aoh_drinks` consists of each `h_drink`.
// A `h_drink` is a row(hash), which consists of three fields sush as `name`, `price` and `caffeine content`.
let aoh_drinks = [
    { name: "Black Coffee", price: 120, "caffeine content": 300 },
    { name: "Green Tea", price: 100, "caffeine content": 200 },
    { name: "Apple Juice", price: 110, "caffeine content": 0 },
    { name: "Iced Chocolate", price: 130, "caffeine content": 0 },
    { name: "Hot Chocolate", price: 105, "caffeine content": 0 },
];


// M21. define s_JSON: Transform a JavaScript variable into a JSON string 
// with two space characters as white space for indentation
// JSON.stringify(value[, replacer[, space]])
// #####################################################################
let s_JSON = JSON.stringify(aoh_drinks, null, 2);


// M31.Output the heading as H5: 
// #####################################################################
dv.span("##### M33.Transform a JavaScript variable into a JSON string");


// M33.Output s_JSON:
// #####################################################################
dv.span(s_JSON);


// M35.Output s_JSON: Require print() in the step M01
// #####################################################################
//print(s_JSON);


Screenshots(DVJS11)

Output by M33.dv.span (Not formatted)
```JSON
M33.Transform a JavaScript variable into a JSON string
[
{
"name": "Black Coffee",
"price": 120,
"caffeine content": 300
},
{
"name": "Green Tea",
"price": 100,
"caffeine content": 200
},
{
"name": "Apple Juice",
"price": 110,
"caffeine content": 0
},
{
"name": "Iced Chocolate",
"price": 130,
"caffeine content": 0
},
{
"name": "Hot Chocolate",
"price": 105,
"caffeine content": 0
}
]
```
Output by M35.print (formatted)
```JSON
M33.Transform a JavaScript variable into a JSON string
[
  {
    "name": "Black Coffee",
    "price": 120,
    "caffeine content": 300
  },
  {
    "name": "Green Tea",
    "price": 100,
    "caffeine content": 200
  },
  {
    "name": "Apple Juice",
    "price": 110,
    "caffeine content": 0
  },
  {
    "name": "Iced Chocolate",
    "price": 130,
    "caffeine content": 0
  },
  {
    "name": "Hot Chocolate",
    "price": 105,
    "caffeine content": 0
  }
]
```

DVJS13_transform_a_JSON_string_into_a_JavaScript_variable

Summary

Main DVJS

Code Name Data type Group By Purposes Remark
DVJS13
_transform
_a_JSON_string
_into
_a_JavaScript_variable
1.s_JSON_from_Q82_DVJS11:
a JSON string

2.aoh_drinks:
an array of hashes
no To parse a JSON string and transform it into a JavaScript variable by using JSON.parse() a JSON string(memory) to a JS variable

Notes

Summary

Q1: What does the following DQL statement mean?

// M21. define aoh_drinks: 
// Parse a JSON string into a JavaScript variable
// JSON.parse(text, reviver)
// #####################################################################
let aoh_drinks = JSON.parse(s_JSON_from_Q82_DVJS11);

A1

  • The above statement means that to parse a JSON string like s_JSON_from_Q82_DVJS11 and transform it into a JavaScript variable like aoh_drinks.

code DVJS13_transform_a_JSON_string_into_a_JavaScript_variable

Summary_code
title: DVJS13_transform_a_JSON_string_into_a_JavaScript_variable =>To parse a JSON string and transform it into a JavaScript variable by using `JSON.parse()`
collapse: close
icon: 
color: 
```dataviewjs
// M11. define s_jsonString_from_DVJS11: 
// The following expression should be copied by yourself from the result of the Q82_DVJS11.
// #####################################################################
let s_JSON_from_Q82_DVJS11 = `
[
  {
    "name": "Black Coffee",
    "price": 120,
    "caffeine content": 300
  },
  {
    "name": "Green Tea",
    "price": 100,
    "caffeine content": 200
  },
  {
    "name": "Apple Juice",
    "price": 110,
    "caffeine content": 0
  },
  {
    "name": "Iced Chocolate",
    "price": 130,
    "caffeine content": 0
  },
  {
    "name": "Hot Chocolate",
    "price": 105,
    "caffeine content": 0
  }
]
`;//<= Never modify it.


// M21. define aoh_drinks: 
// Parse a JSON string into a JavaScript variable
// JSON.parse(text, reviver)
// #####################################################################
let aoh_drinks = JSON.parse(s_JSON_from_Q82_DVJS11);


// M31.Output the heading as H5: 
// #####################################################################
dv.header(5, "M33.Parse a JSON string and transform it into a JavaScript variable");


// M33.Output aoh_drinks:
// #####################################################################
//dv.span(aoh_drinks);
dv.table(
    ["N", "Name", "Price", "Caffeine Content"],
    aoh_drinks.map((h_drink, index) => [
        index + 1,
        h_drink.name,
        h_drink.price,
        h_drink["caffeine content"],
    ])
);


Screenshots(DVJS13)


DVJS21_transform_a_JavaScript_variable_into_a_JSON_file

Summary

Main DVJS

Code Name Data type Group By Purposes Remark
DVJS21
_transform
_a_JavaScript_variable
_into
_a_JSON_file
aoa_drinks:
an array of arrays
no 1.To equire Node.js: Node.js:JavaScript runtime
2.To transform a JavaScript variable into a JSON file
a JS variable to a JSON file

The DVJS21 is based on the heading How to write to JSON files using the fs.writeFile method in the following topic.
- Reading and writing JSON files in Node.js: A complete tutorial

Notes

Summary

To modify the code: M31

  • To define s_file_folder
Original Example
```JS
// M31. define s_file_folder : "D:/in/test"
// #####################################################################
let s_file_folder = "D:/in/test";
```
Another Example
```JS
// M31. define s_file_folder : "D:/in/test"
// #####################################################################
let s_file_folder = "D:/data_exchange/test";
```

To modify the code: M41

  • To define s_filename
Original Example
```JS
// M41. define s_filename: "newX_from_Q82_DVJS21.json"
// #####################################################################
let s_filename = "newX_from_Q82_DVJS21.json";
```
Another Example
```JS
// M41. define s_filename: "newX_from_Q82_DVJS21.json"
// #####################################################################
let s_filename = "aoa_drinks_from_Q82_DVJS21.json";
```

code DVJS21_transform_a_JavaScript_variable_into_a_JSON_file

Summary_code
title: DVJS21_transform_a_JavaScript_variable_into_a_JSON_file =>1.To equire Node.js: [Node.js:JavaScript runtime](https://nodejs.org/en/) 2.To transform a JavaScript variable into a JSON file
collapse: close
icon: 
color: 
```dataviewjs
// M11. define aoa_drinks : aoa = an array of arrays
// #####################################################################
// The `aoa_drinks` consists of each `a_drink`.
// An `a_drink` is a row(array), which consists of three fields sush as `name`, `price` and `caffeine content`.
// "Name", "price", "Caffeine Content"
let aoa_drinks = [
    ["Black Coffee", 120, 300],
    ["Green Tea", 100, 200],
    ["Apple Juice", 110, 0],
    ["Iced Chocolate", 130, 0],
    ["Hot Chocolate", 105, 6],
];


// M21. define s_JSON: Transform a JavaScript variable into a JSON string 
// with two space characters as white space for indentation
// #####################################################################
let s_JSON = JSON.stringify(aoa_drinks, null, 2);


// M30. define fs: require Node.js FS Module
// #####################################################################
const fs = require('fs');


// M31. define s_file_folder : "D:/in/test"
// #####################################################################
let s_file_folder = "D:/in/test";


// M33. create a folder recursively: 
// where s_file_folder doesn't exist
// Creates D:/in/test, regardless of whether `D:/in` and D:/in/test exists.
// #####################################################################
try {
    
    // M33.TRY11 Successfully created a folder recursively:
    // #########################################################
    if (!fs.existsSync(s_file_folder)) {
        fs.mkdirSync(s_file_folder, { recursive: true });
    }

} catch (err) {
    
    // M33.TRY21 Error created a folder recursively: To print messages
    // #########################################################
    dv.span(`##### Error : Folder not created:`);
    dv.span(`##### ${s_file_folder}`);
    
}


// M41. define s_filename: "newX_from_Q82_DVJS21.json"
// #####################################################################
let s_filename = "newX_from_Q82_DVJS21.json";


// M43. define s_output_filepath: "D:/in/test/newX_from_Q82_DVJS21.json"
// #####################################################################
let s_output_filepath = s_file_folder + "/" + s_filename;


// M45. define b_file_exists:  
// #####################################################################
let b_file_exists = true;


// M47. define b_file_exists: To check the existence of s_output_filepath
// fs.existsSync(path): Returns true if the path exists, false otherwise.
// Sync.= Synchronous
// #####################################################################
b_file_exists = fs.existsSync(s_output_filepath);


// M49. check the existence of s_output_filepath:
// To print a message where it exists
// The DVJS21 ONLY creates a new file instead of updating an older file becaue it is too easy to run the DVJS21 in an Obsidian vault. 
// Moreover, the older file may be to be used by the DVJS23.
// #####################################################################
if (b_file_exists) {
    // CASE_01: The file exists.
    dv.span(`##### ${s_output_filepath} exists.`);
    dv.span("##### You have to remove it first.");    
}


// M61. fs.writeFile : 
// Write a JSON string to a local text file where it doesn't exist.
// #####################################################################
if (b_file_exists) {    
    // CASE_01: The file exists.
    // do nothing    
} else {    
    // CASE_02: The file doesn't exist.
    fs.writeFile(s_output_filepath, s_JSON, (err) => {
        
        if (err) {            
            // M61.IF11 Error writing to a local text file: To print messages
            // #########################################################
            dv.span("##### Error writing to a local text file");
            dv.span(err);            
        } else {            
            // M61.IF21 Successfully wrote to a local text file: To print messages
            // #########################################################
            dv.span("##### Successfully wrote to a local text file");            
        }
        
    });
}



Screenshots(DVJS21)

Output
  • filename : D:/in/test/newX_from_Q82_DVJS21.json
```JSON
[
  [
    "Black Coffee",
    120,
    300
  ],
  [
    "Green Tea",
    100,
    200
  ],
  [
    "Apple Juice",
    110,
    0
  ],
  [
    "Iced Chocolate",
    130,
    0
  ],
  [
    "Hot Chocolate",
    105,
    6
  ]
]
```

DVJS23_transform_a_JSON_file_into_a_JavaScript_variable

Summary

Main DVJS

Code Name Data type Group By Purposes Remark
DVJS23
_transform
_a_JSON_file
_into
_a_JavaScript_variable
“D:/in/test/
newX_from_Q82_DVJS21.json”:
a JSON file
no 1.To equire Node.js: Node.js:JavaScript runtime
2.To transform a JSON file into a JavaScript variable like aoa_drinks
a JSON file to a JS variable

The DVJS23 is based on the heading How to read a JSON file in the following topic.
- How to Read, Write and Parse JSON in JavaScript

Notes

Summary

To modify the code: M33

  • To define s_input_filepath
  • The value of s_input_filepath must be the same as the value of s_output_filepath defined in the DVJS21.
Original Example
```JS
// M33. define s_input_filepath:  
// The file was created by the Q82_DVJS21.
// #####################################################################
let s_input_filepath = "D:/in/test/newX_from_Q82_DVJS21.json";
```
Another Example
```JS
// M33. define s_input_filepath:  
// The file was created by the Q82_DVJS21.
// #####################################################################
let s_input_filepath = "D:/data_exchange/test/aoa_drinks_from_Q82_DVJS21.json";
```

To modify the code: M51.TRY11

Original Example
  • To define aoa_drinks
```JS
            // M51.TRY11 Successfully parsed a JSON file: To print messages
            // #########################################################
            let aoa_drinks = JSON.parse(data);
            dv.span("##### Successfully parsed a JSON file");
            dv.table(["Name", "Price", "Caffeine Content"], aoa_drinks);
            //dv.span(aoa_drinks);
```
Another Example
  • To define drinks
```JS
            // M51.TRY11 Successfully parsed a JSON file: To print messages
            // #########################################################
            let drinks = JSON.parse(data);
            dv.span("##### Successfully parsed a JSON file");
            dv.table(["Name", "Price", "Caffeine Content"], drinks);
            //dv.span(drinks);
```

code DVJS23_transform_a_JSON_file_into_a_JavaScript_variable

Summary_code
title: DVJS23_transform_a_JSON_file_into_a_JavaScript_variable =>1.To equire Node.js: [Node.js:JavaScript runtime](https://nodejs.org/en/) 2.To transform a JSON file into a JavaScript variable like `aoa_drinks`
collapse: close
icon: 
color: 
```dataviewjs
// M30. define fs: require Node.js FS Module
// #####################################################################
const fs = require('fs');


// M33. define s_input_filepath:  
// The file was created by the Q82_DVJS21.
// #####################################################################
let s_input_filepath = "D:/in/test/newX_from_Q82_DVJS21.json";


// M35. define b_file_exists:  
// #####################################################################
let b_file_exists = false;


// M37. define b_file_exists: To check the existence of s_input_filepath
// fs.existsSync(path): Returns true if the path exists, false otherwise.
// Sync.= Synchronous
// #####################################################################
b_file_exists = fs.existsSync(s_input_filepath);


// M39. check the existence of s_input_filepath:
// To print a message where it doesn't exist
// #####################################################################
if (b_file_exists) {    
    // CASE_01: The file exists.
    // do nothing
} else {    
    // CASE_02: The file doesn't exist.
    dv.span(`##### ${s_input_filepath} doesn't exist.`);
    dv.span("##### You have to create it first by the Q82_DVJS21.");
}


// M51. fs.readFile :
// Read a JSON file 
// and try to parse it into a JavaScript variable like `aoa_drinks`
// #####################################################################
if (b_file_exists) {    
    // CASE_01: The file exists.
    // #################################################################
    fs.readFile(s_input_filepath, (err, data) => {
        
        // M51.IF10 Error reading a JSON file: To print messages
        // #########################################################
        if (err) {
            dv.span("##### Error reading a JSON file");
            dv.span(err);
        }

        try {
            // M51.TRY11 Successfully parsed a JSON file: To print messages
            // #########################################################
            let aoa_drinks = JSON.parse(data);
            dv.span("##### Successfully parsed a JSON file");
            dv.table(["Name", "Price", "Caffeine Content"], aoa_drinks);
            //dv.span(aoa_drinks);
        } catch (err) {
            // M51.TRY21 Error parsing a JSON file: To print messages
            // #########################################################
            dv.span("##### Error parsing a JSON file");
            dv.span(err);
        }
    });

} else {    
    // CASE_02: The file doesn't exist.
    // #####################################################################
    // do nothing
    // exit the code
}




Screenshots(DVJS23)

Input
  • filename : D:/in/test/newX_from_Q82_DVJS21.json
```JSON
[
  [
    "Black Coffee",
    120,
    300
  ],
  [
    "Green Tea",
    100,
    200
  ],
  [
    "Apple Juice",
    110,
    0
  ],
  [
    "Iced Chocolate",
    130,
    0
  ],
  [
    "Hot Chocolate",
    105,
    6
  ]
]
```
Output(DVJS23)


Related resources

Summary

1 Like