From: "Dave MacFarlane" <driusan@driusan.net>
To: 9front@9front.org
Subject: [9front] libjson can print invalid json
Date: Thu, 17 Nov 2022 16:52:46 -0500 [thread overview]
Message-ID: <923270033661C2AB404C7473549B4808@driusan.net> (raw)
print("%J", json); can print invalid json if a JSON string in the object has a quotation mark in it.
I just threw together this patch to try and escape the strings from printjson() if anyone's interested
in it.
diff 30c5296f32b87d83529d772732726891e1261c9c uncommitted
--- a/sys/src/libjson/printjson.c
+++ b/sys/src/libjson/printjson.c
@@ -52,6 +52,38 @@
}
static int
+printstring(Fmt *f, char *s)
+{
+ int slen = strlen(s);
+ int i, nq=0;
+ int r;
+ char *dup, lastq;
+ for(i = 0; i < slen; i++)
+ if (s[i] == '"') nq++;
+
+ if (nq == 0)
+ return fmtprint(f, "\"%s\"", s);
+
+ r = fmtprint(f, "\"");
+
+ dup = strdup(s);
+ lastq = -1;
+ for(i = 0; i < slen; i++){
+ if(dup[i] == '"') {
+ dup[i] = 0;
+ r += fmtprint(f, "%s\\\"", &dup[lastq+1]);
+ lastq = i;
+ }
+ }
+
+ if (lastq != slen-1)
+ r += fmtprint(f, "%s", &dup[lastq+1]);
+ r += fmtprint(f, "\"");
+ free(dup);
+ return r;
+}
+
+static int
printjson(Fmt *f, JSON *j, int indent)
{
switch(j->t){
@@ -65,7 +97,7 @@
return fmtprint(f, "%f", j->n);
break;
case JSONString:
- return fmtprint(f, "\"%s\"", j->s);
+ return printstring(f, j->s);
break;
case JSONArray:
return printarray(f, j, indent+1);
next reply other threads:[~2022-11-17 21:54 UTC|newest]
Thread overview: 4+ messages / expand[flat|nested] mbox.gz Atom feed top
2022-11-17 21:52 Dave MacFarlane [this message]
2022-11-18 4:30 ` ori
2022-11-18 14:37 ` Dave MacFarlane
2022-11-18 14:52 ` Dave MacFarlane
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=923270033661C2AB404C7473549B4808@driusan.net \
--to=driusan@driusan.net \
--cc=9front@9front.org \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).