5
\$\begingroup\$

Introduction

I've seen throughout the code-golf challenges several simple tasks involving JSON, such as interpreting JSON strings with RegExs, and almost every other manipulation I could think of.

In a binding for AppleScript that I was using for a Node project, I noticed that objects would be returned in a strange way: there would be an array of properties in string form, instead of a JSON object being returned as expected. This is where the challenge comes in...

Algorithm

  1. Add { to beginning of the output string
  2. Iterate over all entries, adding them to the output string, delimited by ,
  3. Add } to the end of the output string
  4. Print out the output string

Challenge

Make this strange return format usable. Convert an array of JSON 'key:value's (in string form) to a full JSON object string.

Rules

  • Any language that can do string manipulations allowed
  • Must print out JSON string with surrounding curly braces {}, and double quotes "" around string values AND all properties ("property":"value" or "property":3.14, etc.)
  • Must return a valid, parseable JSON string
  • Lowest byte count wins per language

Example Input and Output

Input:

['prop1:"val1"', 'prop2:12', 'prop3:3.14', 'prop4:false']

Output:

'{"prop1":"val1", "prop2":12, "prop3":3.14, "prop4":false}'

\$\endgroup\$
10
  • 1
    \$\begingroup\$ Welcome to ppcg.SE! Hope you have a great time here. \$\endgroup\$
    – Leaky Nun
    Jun 11, 2018 at 2:10
  • 1
    \$\begingroup\$ We don't put languages in boxes ^^ \$\endgroup\$
    – Leaky Nun
    Jun 11, 2018 at 2:10
  • 2
    \$\begingroup\$ This challenge seems to be a code-golf challenge, but it doesn't say in the post. Could you make it more clear? \$\endgroup\$ Jun 11, 2018 at 2:11
  • 1
    \$\begingroup\$ Hello, and welcome to the site. I'm voting to close this as unclear. There are a couple of things I find unclear. The first is that terms like "golfing" and "functional" languages are unclear, there are tons of edge cases. I'd recommend getting rid of the bonuses altogether, which would make this challenge clearer and better. It's also not clear to me exactly what the process is to change the strings to json is. I think it ought to be defined much more concretely. \$\endgroup\$
    – Wheat Wizard
    Jun 11, 2018 at 2:39
  • 1
    \$\begingroup\$ Your test case does not seem to match your description. In the test case it seems that quotations were placed around attribute names, but that is not apparent in your specification. \$\endgroup\$
    – Wheat Wizard
    Jun 11, 2018 at 3:05

9 Answers 9

2
\$\begingroup\$

JavaScript (Node.js), 35 bytes

a=>JSON.stringify(eval(`({${a}})`))

Try it online! 43 bytes without builtins:

a=>`{${a.map(s=>s.replace(/\w+/,`"$&"`))}}`

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Retina, 23 bytes

%0`\w+
"$&"
¶
,
.+
{$&}

Try it online! Explanation:

%0`\w+
"$&"

Quote all of the keys.

¶
,

Join the array elements together.

.+
{$&}

Wrap the result in brackets. This can also be done using the following code for the same byte count:

^
{
$
}
\$\endgroup\$
1
\$\begingroup\$

C 108

Thanks to Jonathan Frech this answer is now incredibly shorter
Thanks to @ceilingcat for some very nice pieces of golfing - now even shorter

i;main(c,v)char**v;{for(;++i<c;printf("%c\"%s\":%s",!~-i*79+44,v[i],++*v))*(*v=index(i[v],58))=0;puts("}");}

Try it online!

\$\endgroup\$
4
  • \$\begingroup\$ 113 bytes, keeping with using a main function. \$\endgroup\$ Jun 11, 2018 at 16:57
  • \$\begingroup\$ 112 bytes. \$\endgroup\$ Jun 11, 2018 at 21:09
  • \$\begingroup\$ @JonathanFrech I would never have come up with !~-i++*79+44 That's not just golfed better - it's a better answer. Do you want to post it separately or shall i edit my answer? \$\endgroup\$ Jun 12, 2018 at 5:18
  • 1
    \$\begingroup\$ Regarding the golf: (i==1?"{":",") <-> (i==1?'{':',') (when using %c instead of %s) <-> (i==1?123:44) (substituting actual ASCII values) <-> 44+(123-44)*(i==1) <-> 44+79*(i==1) <-> 44+79*!(i!=1) <-> 44+79*!(i-1) <-> 44+79*!~-i <-> !~-i*79+44. The post-increment was used with regards to the entire program (not locally explainable). Regarding the posting: feel free to use the golfs in your post. \$\endgroup\$ Jun 12, 2018 at 16:57
1
\$\begingroup\$

Scala, 79 bytes

Essentially Neil's JS solve.


Try it online!

def f(a:Seq[String])="{"+a.map(_.replaceAll("\\w+","\"$0\"")).mkString(",")+"}"
\$\endgroup\$
0
\$\begingroup\$

Python 3, 59 bytes

lambda x:"{%s}"%",".join('"'+a.replace(":",'":')for a in x)

Try it online!

-6 bytes thanks to ovs

\$\endgroup\$
1
  • \$\begingroup\$ 59 bytes using a.replace(':','":') \$\endgroup\$
    – ovs
    Jun 11, 2018 at 17:13
0
\$\begingroup\$

Lua, 122 bytes

loadstring[[s="{"for i,v in ipairs(...)do x,y=v:match("(.-):(.+)")s=s.."\""..x.."\":"..y..","end return s:sub(1,-2).."}"]]

Try it online!


This is an anonymous function. It technically doesn't "print out JSON string [...]", but instead it returns this string, so that when calling it you could print. I did that because I needed to first convert the input from string to an actual list, and I did that on the argument of the function call.

If this makes my answer invalid I'll move the string to table (list) "parser" from the footer to the actual code. But I don't think it should, because the input shown as a table, so the code that takes a string and transforms it into a table shouldn't count.

\$\endgroup\$
0
\$\begingroup\$

Go, 116 bytes

import."strings"
func f(s[]string)string{for i,l:=range s{s[i]=`"`+Replace(l,`:`,`":`,1)}
return"{"+Join(s,",")+"}"}

Attempt This Online!

\$\endgroup\$
0
\$\begingroup\$

Ruby, 41 40 bytes

->a{?{+a.map{_1.sub /\w+/,'"\&"'}*?,+?}}

Essentially Neil's JS solve.

Attempt This Online!

\$\endgroup\$
0
\$\begingroup\$

POSIX sh (sed + ShellShoccar-jpn/Parsrs makrj.sh), 33 bytes

Assumes values may have colons but properties shall never have colons, spaces, tabs, or periods.

sed 's/\([^:]*\):/.\1 /'|makrj.sh

Usage

Input via standard input. Each line represents each item of an array.

Commented

# "prop:item"
sed 's/\([^:]*\):/.\1 /'|
# ".prop item" is JSONPath-value format
makrj.sh
# JSON object

Example run on Termux

~ $ sh makrj.sh -h
Usage : makrj.sh [JSON_value_textfile]
Wed Sep 14 22:19:55 JST 2016
~ $ cat jsss;echo;cat jsss | sed 's/\([^:]*\):/.\1 /'|sh makrj.sh
prop1:"val1"
prop2:12
prop3:3.14
prop4:false

{
"prop1":"val1",
"prop2":12,
"prop3":3.14,
"prop4":false
}
~$
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.