I made a script in Python to convert a text file for JSON (for vscode user snippet)

Introduction

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)

Source code

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)
  1. Replace all " with \ "
  2. Replace all tab spaces with \ t
  3. Add 3 tab blanks and " at the beginning of every line and ", at the end of the line
  4. Add " at the very end of the document

The 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 actually used it

Execution environment

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.)

Preparation

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.

Practice

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.

Summary

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

I made a script in Python to convert a text file for JSON (for vscode user snippet)
[VSCode] I made a user snippet for Python print f-string
I made a script in python to convert .md files to Scrapbox format
I made a script to put a snippet in README.md
Convert Excel file to text in Python for diff purposes
I made a python dictionary file for Neocomplete
How to create a JSON file in Python
I made a program to check the size of a file in Python
Parse a JSON string written to a file in Python
A memorandum to run a python script in a bat file
I want to randomly sample a file in Python
I made a python text
Python script to create a JSON file from a CSV file
I created a script to check if English is entered in the specified position of the JSON file in Python.
I tried to convert a Python file to EXE (Recursion error supported)
Python> I made a test code for my own external file
I wrote a function to load a Git extension script in Python
I wrote a script to extract a web page link in Python
I made a library that adds docstring to a Python stub file.
I made a payroll program in Python!
Convert psd file to png in Python
I made a script to display emoji
I made a configuration file with Python
I made a Docker container to use JUMAN ++, KNP, python (for pyKNP).
I wrote a code to convert quaternions to z-y-x Euler angles in Python
Create a shortcut to run a Python file in VScode on your terminal
I made a web application in Python that converts Markdown to HTML
I made a CLI tool to convert images in each directory to PDF
I want to convert a table converted to PDF in Python back to CSV
I tried to develop a Formatter that outputs Python logs in JSON
I want to create a window in Python
I want to write to a file with Python
I made a Caesar cryptographic program in Python.
A story when a Python user passes a JSON file
I tried to create a class that can easily serialize Json in Python
I made a module in C language to filter images loaded by Python
I made a tool to generate Markdown from the exported Scrapbox JSON file
I searched for the skills needed to become a web engineer in Python
I made a script to record the active window using win32gui of Python
How to convert / restore a string with [] in python
I want to embed a variable in a Python string
I want to easily implement a timeout in python
I made a prime number generation program in Python
I made a user management tool for Let's Chat
Convert a text file with hexadecimal values to a binary file
I want to write in Python! (2) Let's write a test
I made a VM that runs OpenCV for Python
I tried to implement a pseudo pachislot in Python
I made a Python module to translate comment outs
I made a code to convert illustration2vec to keras model
How to convert JSON file to CSV file with Python Pandas
I want to work with a robot in python.
[Python] I made a classifier for irises [Machine learning]
Convert / return class object to JSON format in Python
I made a prime number generation program in Python 2
[Python] Created a method to convert radix in 1 second
I made a python library to do rolling rank
I was soberly addicted to calling awscli from a Python 2.7 script registered in crontab
I made a program to convert images into ASCII art with Python and OpenCV
I can't sleep until I build a server !! (Introduction to Python server made in one day)
Assigned scaffolding macro in Python script file to F12 key