Last active
March 31, 2023 07:53
-
-
Save izmailoff/966aa0e2b7379324b502 to your computer and use it in GitHub Desktop.
Convert `Content-Type: multipart/form-data` to JSON format because I can't read the former
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object FormFieldsToJson extends App { | |
if(args.length != 1) { | |
println("Usage: FormDataParser <form data>") | |
System.exit(1) | |
} | |
val fieldDelimiter = "----" | |
val fieldNLines = 3 | |
val data = args(0) | |
val nameRegex = """^.+name="(.+)"$""".r | |
val rawFields = data | |
.split('\n') | |
.dropWhile(! _.startsWith(fieldDelimiter)) | |
.filter(! _.startsWith(fieldDelimiter)) | |
.grouped(fieldNLines) | |
val fields = for { | |
Array(one, two, three) <- rawFields | |
fieldName = one match { case nameRegex(n) => n; case _ => "na" } | |
fieldValue = two.trim + three | |
} yield fieldName -> fieldValue | |
val jsonFields = fields map { case (k,v) => s""" "$k" : "$v"""" } | |
val jsonDoc = s"{\n${jsonFields.mkString(",\n")}\n}" | |
println(jsonDoc) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How to use.
Compile:
Get some data:
Run it:
Prints: