I'm currently studying web production, but when registering user snippets with VS Code, it was troublesome to add double quotes to the beginning and end of each line. I made my own python script that converts the contents of the file into a form that is easy to use with JSON. (The reason why it's web but not JavaScript is because I'm not used to it yet. Sweat)
conv stands for conversion
json_conv.py
'''
A script that converts the text in the target file so that it can be used as a JSON value.
(i)All of"""Behind"\\", And
(ii)Tab symbol for all tab inputs(\\t)Replace with
(iii)3 tabs at the beginning of every line and """, At the end of the line"",", And
(iv)At the very end of the document""Is added.
First argument file(input_file)Is converted based on, and the result is the file of the second argument(output_file)Write to.
(output_If file is not specified, input_Overwrite file as it is)
You can also import a function with the same name as a module.
(How to write a command)
> python -m json_conv.py (input_file) (output_file(Any))
'''
def json_conv(input_file, output_file=None, n_tab=3):
'''
A function that converts the text in the target file so that it can be used as a JSON value.
(i)All of"""Behind"\\", And
(ii)Tab symbol for all tab inputs(\\t)Replace with
(iii)At the beginning of every line(n_tab)Tab input and """, At the end of the line"",", And
(iv)At the very end of the document""Is added.
Number of tab inputs to insert at the beginning of a line(n_tab)The default for is 3.
input_Convert from file and output the result_Write to file.
(output_If file is not specified, input_Overwrite file as it is)
'''
# output_If you do not specify file, input_Set file as the output destination
if output_file is None:
output_file = input_file
with open(input_file, mode="r", encoding="utf-8") as file:
processed_txt = "" #Define a string for output
for line in file:
replaced_line = line.replace('\"', '\\\"') #"" In the document"""\"Replaced with
replaced_line = replaced_line.replace("\t", "\\t") #Tab input tab symbol(\t)Replace with
replaced_line = replaced_line.replace('\n', '\",\n') #Immediately before a line break(=End of line)To "",Insert
processed_line = '\t' * n_tab + '\"' + replaced_line #At the beginning of the line(n_tab)Tabs and ""Insert (n in the argument)_If tab is not specified, 3 tabs will be inserted)
processed_txt += processed_line #Add processed lines to output string
processed_txt += "\"" #The very end of the document(=\End of line without n)To """Add
print("\n Save destination: " + output_file + "\n")
print("Converted document")
print("-----------------------------------------\n")
print(processed_txt)
print("\n-----------------------------------------\n")
while True:
#You will be asked if you really want to write to the specified file
answer = input("Are you sure you want to save it in the specified file? (If it already exists, it will be overwritten)(y/n) ")
#If y is selected, output_Write the converted document to the file specified in file(Input by default_Overwrite file)
if answer == 'y':
with open(output_file, mode="w", encoding="utf-8") as file:
file.write(processed_txt)
break
#If n is selected, exit without writing
if answer == 'n':
break
#If you enter anything else, you will be asked again
else:
continue
#Processing when executed on the command line
if __name__ == "__main__":
import sys
try:
selected_input = sys.argv[1] #Specify the first command line argument as the conversion source file
#Raise an error if no command line arguments are passed
except IndexError:
raise TypeError("No input file specified")
try:
selected_output = sys.argv[2] #Specify the second argument of the command line as the save destination of the converted file
json_conv(selected_input, selected_output) #Execute function for conversion
except IndexError:
json_conv(selected_input) #If you don't specify the second argument, pass only the first argument and execute the function(Overwrite the source file)
"
with \ "
\ t
"
at the beginning of every line and ",
at the end of the line"
at the very end of the documentThe process is performed in order.
In JSON, I got an error if there was a space due to a tab, so I replaced the tab with \ t
. The reason for escaping "
first is that otherwise "
will enclose each line in a strange way.
Also, in docstring, in order to correct the display when the function is hovered by mouse with vscode, it is escaped by adding \
after \
.
I defined it as a function so that it can also be used as a module.
In the function, by specifying n_tab
, the number of tab blanks inserted at the beginning of the line can be adjusted, but it has not been implemented on the command line ...
Someday, if you feel like it, you may be able to adjust it on the command line as well.
I'm using Anaconda Power Shell as a terminal for Visual Studio Code and running it in Anaconda's base environment. (Even if you don't use Visual Studio Code or Anaconda, if you can use python on a shell such as a command prompt or Windows Power Shell, it will probably work fine.)
Place json_conv.py in a directory that has a module path so that it can be imported as a module.
If you don't know how to pass the pass, the following article will be helpful. How to set environment variables such as Temp and Path in Windows 10|service|Professional engineer [Python environment construction] Explanation of environment variables! | WEBCAMP NAVI
I make one directory to put my own scripts together, and add the path of the directory for my own scripts to PYTHONPATH and use it.
For example, suppose you write this code.
test.html
<ul class="_list">
<li class="_listItem">
<div class="_listWrapper">
<img class="_listImg" src="" alt="">
<div class="_listContent">
</div>
</div>
</li>
</ul>
Open a shell, use the cd command to change to the directory containing test.html, and then run the following command:
(Python -m
is a command to execute a Python module as a script. Note that json_conv is not followed by .py because it is a module name.)
python -m json_conv test.html
Then, the following screen will be displayed in the shell.
Destination: test.html
Converted document
-----------------------------------------
"<ul class=\"_list\">",
"\t<li class=\"_listItem\">",
"\t\t<div class=\"_listWrapper\">",
"\t\t\t<img class=\"_listImg\" src=\"\" alt=\"\">",
"\t\t\t<div class=\"_listContent\">",
"\t\t\t\t",
"\t\t\t</div>",
"\t\t</div>",
"\t</li>",
"</ul>"
-----------------------------------------
Are you sure you want to save it in the specified file? (Overwritten if it already exists
Will be)(y/n)
If you enter n
here, the program will end without doing anything.
If you enter y
, test.html will be overwritten and will look like this:
test.html
"<ul class=\"_list\">",
"\t<li class=\"_listItem\">",
"\t\t<div class=\"_listWrapper\">",
"\t\t\t<img class=\"_listImg\" src=\"\" alt=\"\">",
"\t\t\t<div class=\"_listContent\">",
"\t\t\t\t",
"\t\t\t</div>",
"\t\t</div>",
"\t</li>",
"</ul>"
By converting in this way, you can use it as a JSON value just by copying and pasting, so you can easily create a VS Code user snippet.
"Print to console": {
"prefix": "log",
"body": [
"console.log('$1');",
"$2"
],
"description": "Log output to console"
}
It is written at the beginning of html.json, ↑ The body part of this template is the previous one If you replace it with the converted code and then rewrite the prefix and description ...
html.json
"list with image": {
"prefix": "listImg",
"body": [
"<ul class=\"_list\">",
"\t<li class=\"_listItem\">",
"\t\t<div class=\"_listWrapper\">",
"\t\t\t<img class=\"_listImg\" src=\"\" alt=\"\">",
"\t\t\t<div class=\"_listContent\">",
"\t\t\t\t",
"\t\t\t</div>",
"\t\t</div>",
"\t</li>",
"</ul>" ],
"description": "a list, each of its row has an image and texts."
}
That's all there is to it.
In this way, you can easily create user snippets by executing a single command without having to manually write or escape "
.
If you want to create a user snippet, you can create it by creating an appropriate file, writing code in it, and executing this command.
This time, I introduced a python script to convert the written code for JSON. I basically made it for myself, so I'm sorry if something goes wrong. Sweat
This time I made it for JSON,
for line in file:
replaced_line = line.replace('\"', '\\\"') #"" In the document"""\"Replaced with
replaced_line = replaced_line.replace("\t", "\\t") #Tab input tab symbol(\t)Replace with
replaced_line = replaced_line.replace('\n', '\",\n') #Immediately before a line break(=End of line)To "",Insert
processed_line = '\t' * n_tab + '\"' + replaced_line #At the beginning of the line(n_tab)Tabs and ""Insert (n in the argument)_If tab is not specified, 3 tabs will be inserted)
processed_txt += processed_line #Add processed lines to output string
processed_txt += "\"" #The very end of the document(=\End of line without n)To """Add
If you rewrite here, which is actually processing the sentence, you can use it for other conversions.
Someday we may make a more versatile version.
Recommended Posts