Convert a txt file into JSON

txt to json converter online
how to convert text file to json in python
convert text file to json javascript
convert text file to json format in java
read text file as json python
how to convert text data into json format
json file converter
convert log file to json python

I need to convert a simple txt list into a specific json format.

My list looks like this :

server1
server2
server3
server4

I need to have a JSON output that would look like this :

{ "data": [
 { "{SERVER}":"server1" },
 { "{SERVER}":"server2" },
 { "{SERVER}":"server3" },
 { "{SERVER}":"server4" }
]}

I was able to generate this with a bash script but I don't know how to remove the comma for the last line. The list is dynamic and can have a different amount of servers every time the script is run. Any tip please ?

EDIT : my current code :

echo "{ "data": [" > /tmp/json_output
for srv in `cat /tmp/list`; do
echo "{ \"{SERVER}\":\"$srv\" }," >> /tmp/json_output
done
echo "]}" >> /tmp/json_output

I'm very new at this, sorry if I sound noobish.

I would use jq for this.

$ jq -nR 'reduce inputs as $i ([]; .+[$i]) | map ({"{SERVER}": .}) | {data: .}' tmp.txt
{
  "data": [
    {
      "{SERVER}": "server1"
    },
    {
      "{SERVER}": "server2"
    },
    {
      "{SERVER}": "server3"
    },
    {
      "{SERVER}": "server4"
    }
  ]
}

(It seems to me there should be an easier way to produce the array ["server1", "server2", "server3", "server4"] to feed to the map filter, but this is functional.)


Breaking this down piece by piece, we first create an array of your server names.

$ jq -nR 'reduce inputs as $item ([]; .+[$item])' tmp.txt
[
  "server1",
  "server2",
  "server3",
  "server4"
]

This array is fed to a map filter that creates an array of objects with the {SERVER} key:

$ jq -nR 'reduce inputs as $item ([]; .+[$item]) | map ({"{SERVER}": .})' tmp.txt
[
  {
    "{SERVER}": "server1"
  },
  {
    "{SERVER}": "server2"
  },
  {
    "{SERVER}": "server3"
  },
  {
    "{SERVER}": "server4"
  }
]

And finally, this is used to create an object that maps the key data to the array of objects, as shown at the top.

Convert Text file to JSON in Python, or any other format you need as a result (more than 200 formats supported) The data in a json file are stored in simple text file format and the content is viewable in any simple text editor. It originates as a way to represent objects in JavaScript, but most modern programming languages or applications will have built-in functionality for working with JSON file format.

This is very easy for Xidel:

xidel -s input.txt -e '{"data":[x:lines($raw) ! {"{SERVER}":.}]}'
{
  "data": [
    {
      "{SERVER}": "server1"
    },
    {
      "{SERVER}": "server2"
    },
    {
      "{SERVER}": "server3"
    },
    {
      "{SERVER}": "server4"
    }
  ]
}

x:lines($raw) is a shorthand for tokenize($raw,'\r\n?|\n'). It creates an array of every new line.

In human terms you can see x:lines($raw) ! {"{SERVER}":.} as "create a JSON object for every new line".

See also this xidelcgi demo.

Convert .txt file to JSON, To handle the data flow in a file, the JSON library in Python uses dump() function to convert the Python objects into their respective JSON object,� Converting a file txt.. file json. Online converter. Transform a file txt.. SEND EYO TAGS : pdf converter, turn video into gif, convert mov to avi, aiff to mp3

As others said a tool like jq should better be used. Alternatively, you could use an array and determine whether the element you process is the last or not, for example your code could be :

declare -a servers
servers=($(cat /tmp/list))
pos=$(( ${#servers[*]} - 1 ))
last=${servers[$pos]}

echo "{ "data": [" > /tmp/json_output
for srv in "${servers[@]}"; do
if [[ $srv == $last ]]
then
        echo "{ \"{SERVER}\":\"$srv\" }" >> /tmp/json_output
else
        echo "{ \"{SERVER}\":\"$srv\" }," >> /tmp/json_output
fi
done
echo "]}" >> /tmp/json_output

Convert txt json.. Online converter. Converting a file txt , You can try to use tsv2json this tool can reads a tsv file from stdin and writes a json file to stdout. It's distributed in source file, to compile it you� Please understand.txt is an extension and json is the data format. in order to convert anything to json there has to be some sort of relation like key-value pair, table-column etc.. an unstructured text file can not be directly converted to json format. – Abhinay Oct 1 '16 at 7:01

You can do this using Python 3 :

#!/usr/local/bin/python3

import os
import json

d = []
with open('listofservers.txt', 'r', encoding='utf-8') as f:
    for server in f:
        d.append({'{Server}' : server.rstrip("\n")})

print(json.dumps({'data': d}, indent=" "))

Which will print :

{
 "data": [
  {
   "{Server}": "server1"
  },
  {
   "{Server}": "server2"
  },
  {
   "{Server}": "server3"
  },
  {
   "{Server}": "server4"
  }
 ]
}

txt-file-to-json, Convert txt json.. Online converter. Converting a file txt.. file json. Online converter . Transform a file txt.. convert image-jpeg to json I have data in a text file named data.txt, like. 1. John (1994) 92 2. Granny (1972) 82 I want to convert this data to JSON format using Awk. Expected result:

Convert TXT file to JSON file, Learn about our RFC process, Open RFC meetings & more.Join in the discussion ! � txt-file-to-json. 3.0.6 • Public • Published 6 months ago. You need to read the content of file. obj, end = self.raw_decode(s, idx=_w(s, 0).end()) TypeError: expected string or buffer import json f = open("string.txt", 'w') f1 = open("stringJson.txt", 'r') data = json.loads(f1) f.write(json.dumps(data, indent=1)) f.close()

Convert text to JSON, Look for software to Convert TXT file to JSON file without programming ? Try Witdata DataFileConverter Now! No need to program, just a few� batch_to_json(file_dicts) - Convert multiple sas7bdat files into json files at once. file_dicts = A list containing a dictionary for each file to convert. The dictionary is required to contain 'sas7bdat_file' containing the path and name for the sas7bdat file, and 'export_file' containing the path and name for the json files.

Convert text to json object file, Convert text to JSON. Having the input txt file example.txt, how can I easily convert this into JSON? Each indented line is a new array in JSON. JSON To Text Converter helps you to convert JSON code to text format online.

Comments
  • Show us your code and where it fails, thanks
  • Use a program like jq to generate the JSON from your input.
  • The filter could be this: {data:[{"{SERVER}":inputs}]} (with -Rn)
  • @chepner Thanks!