0

I have a space separated list of names generated by a program, I need to convert this list to json. I can not change the program generating the file output. I need to convert the output in file names.txt to json.

example: file output is called names.txt. context is below.

name1 name2 name3

The json expectation is

{
    "names": [
        "name1",
        "name2",
        "name3"
    ]
}

I have and at my disposal.

peak
  • 105,803
  • 17
  • 152
  • 177
Wiked0ne
  • 3
  • 1

3 Answers3

2

A solution could be simplefied by passing the 'string' as argument, then using split() to create an array like so:

jq -n --arg d "$(cat input)" '{ "names": $d | split(" ") }'

Local example:

$ cat input
name1 name2 name3
$
$ jq -n --arg d "$(cat input)" '{ "names": $d | split(" ") }'
{
  "names": [
    "name1",
    "name2",
    "name3"
  ]
}
$
$
0stone0
  • 34,288
  • 4
  • 39
  • 64
0

Open the file and use dictionary comprehension

with open('names.txt') as file:
    d = {'names': name.split(' ') for name in file}
    
print(d)
It_is_Chris
  • 13,504
  • 2
  • 23
  • 41
0

You can just read the first line, split on whitespace, the create the desired dictionary

with open('names.txt') as f:
    names = f.readline().spilt()
    data = {'names': names}

To later get this into valid json you can use dump or dumps depending what you need to pass this to

>>> import json
>>> json.dumps(data)
'{"names": ["name1", "name2", "name3"]}'
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218