Sponsored Content
Top Forums Shell Programming and Scripting Tweak python program to give result in json Post 302992720 by ashokvpp on Wednesday 1st of March 2017 03:19:11 AM
Old 03-01-2017
Tweak python program to give result in json

Hi ,

Below is the script which prints result in json but when i validate it has some tab or extra space issues.

JSON result
Code:
{

    "data":[

    { "{#NAME}":"lilly-54b91f8-2
"}
,

    { "{#NAME}":"silly-54b91f8-2
"}
,

    { "{#NAME}":"milly-54b91f8-2
"}
,

    { "{#NAME}":"sollys-54b91f8-2
"}

    ]

}

This is the line I tweaked. Please advise.
Code:
  print "\t{",  "\"{#NAME}\":\""+container['Names'][0][1:]+hn+"\"}"

Code:
#!/usr/bin/env python
#
from docker import Client
from optparse import OptionParser
import json

class DockerService(object):

    def __init__(self, url):

        self.url = url
        self.docker_running = False

    def list_containers(self):

        docker_conn_list = Client(base_url=self.url)

        try:
            containerlist = docker_conn_list.containers()
            self.docker_running = True
        except Exception:
            self.docker_running = False

        if self.docker_running:
            return containerlist

def main():

    parser = OptionParser()
    parser.add_option('-u', '--url', default='unix://var/run/docker.sock',
                      help='URL for Docker service (Unix or TCP socket).')
    (opts, args) = parser.parse_args() 

    docker_service = DockerService(opts.url)
    containerslist = docker_service.list_containers()

    file = open('/tmp/hostname','r')
    hn = file.read()
   # print hn

    first = 1;
    print "{\n";
    print "\t\"data\":[\n";

    for container in containerslist:

        if first == 0:
            print ",\n"
        first = 0
        print "\t{",  "\"{#NAME}\":\""+container['Names'][0][1:]+hn+"\"}"



    print "\n\t]\n"
    print "}\n"

if __name__ == '__main__':
    main()

 

10 More Discussions You Might Find Interesting

1. HP-UX

get program name give a process id

Hi , I have query regarding to get a program name given a pid in HP-Ux . give procees id ( PID) i would like to retrieve the process/program through a C program ? my input to c program will be will be pid and i would like to know what is process name /program name . Many Thanks ... (1 Reply)
Discussion started by: naren_chella
1 Replies

2. UNIX for Advanced & Expert Users

executing script by cron doesnt give me expected result

Hi frnds... I m facing very irritating problem already waisted my 2 days.. I have a following script..( i am pasting only the main code) ftp -ivn 213.194.40.77 <<FTP user $user $password binary cd $FileDir/out lcd $localpath get $file rename $FileDir/out/$file $FileDir/tmp/$file... (1 Reply)
Discussion started by: clx
1 Replies

3. Programming

Please give me some advise to program for unix/linux using c/c++?

I have a good foundation of c++.I want to learn to program for linux/unix,can you give me some advises,for example classic books ,which operating system is used better(freebsd,solaris,federal linux.etc),and which aspects uses mostly in job.Can you give me clear direction for working or learning. (1 Reply)
Discussion started by: fengshuiyue
1 Replies

4. Programming

Python program faster than C++ program.

I wrote a simple program that generates a random word 10,000,000 times. I wrote it in python, then in C++ and compared the two completion times. The python script was faster! Is that normal? Why would the python script be faster? I was under the impression that C++ was faster. What are some of... (2 Replies)
Discussion started by: cbreiny
2 Replies

5. Shell Programming and Scripting

How to give runtime arguments to different program

I have a shell script that is attempting to call a c program. I call the c program with ./dictool dictool accepts arguments at runtime. It works by prompting the user for various commands, acting on those commands, spitting out an output, and then prompting for more commands. My question is,... (1 Reply)
Discussion started by: aarongoldfein
1 Replies

6. Shell Programming and Scripting

[Solved] My sed command not give me a satisfy result

This is my command echo "Test" | sed -f <(sed -e 's/.*/s,&,gI/' mydic) In mydic file,containing 2 columns delimit by comma (,) a,AlphabetA . . . e,AlphabetE . . s,AlphabetS . t,AlphabetT test,testedd . . zebra,zebraaaa The expect result is testedd (0 Replies)
Discussion started by: Runicer
0 Replies

7. Shell Programming and Scripting

How to give a text file as input while running a program?

Hi Friends, I am running a program /path/to/program -i 1 100 -o /path/to/output/op_1_100.txt In the above command, I have to try various number of combinations at the -i parameter and the output file name varies with each combination. Now, I have my -i parameter text file, which is like... (4 Replies)
Discussion started by: jacobs.smith
4 Replies

8. Programming

Json dissect with python

hello, I'm trying to parse a json file and print out each element along with some related infos such type and value. I would like to do that in python and I found a nice support to quickly load the json file, instead I found a bit more difficult the information extraction. Example, I have... (0 Replies)
Discussion started by: Dedalus
0 Replies

9. Emergency UNIX and Linux Support

How to take awk result out (piping to other program)?

Hi! all here is my code which is working fine no errors but I want to know how to take result and input to other program awk 'FNR==1{i++}{LC=NR} {for(k=1; k<=NF; k++) A=$k} END{for (i=1;i<=LC;i++) { for(j=1;j<=LC;j++) if(A=='$UID' && A>='$MX'+A &&... (7 Replies)
Discussion started by: Akshay Hegde
7 Replies

10. Programming

Java HTTP PUT Request/JSON Not Working But Using Python It Does ?

I have some code that I have been playing around with learning Java: import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; ... (1 Reply)
Discussion started by: metallica1973
1 Replies
RDF::Trine::Parser(3pm) 				User Contributed Perl Documentation				   RDF::Trine::Parser(3pm)

NAME
RDF::Trine::Parser - RDF Parser class VERSION
This document describes RDF::Trine::Parser version 1.000 SYNOPSIS
use RDF::Trine::Parser; RDF::Trine::Parser->parse_url_into_model( $url, $model ); my $parser = RDF::Trine::Parser->new( 'turtle' ); $parser->parse_into_model( $base_uri, $rdf, $model ); $parser->parse_file_into_model( $base_uri, 'data.ttl', $model ); DESCRIPTION
RDF::Trine::Parser is a base class for RDF parsers. It may be used as a factory class for constructing parser objects by name or media type with the "new" method, or used to abstract away the logic of choosing a parser based on the media type of RDF content retrieved over the network with the "parse_url_into_model" method. METHODS
"media_type" Returns the canonical media type associated with this parser. "media_types" Returns the media types associated with this parser. "parser_by_media_type ( $media_type )" Returns the parser class appropriate for parsing content of the specified media type. "guess_parser_by_filename ( $filename )" Returns the best-guess parser class to parse a file with the given filename. "new ( $parser_name, @args )" Returns a new RDF::Trine::Parser object for the parser with the specified name (e.g. "rdfxml" or "turtle"). If no parser with the specified name is found, throws a RDF::Trine::Error::ParserError exception. Any @args will be passed through to the format-specific parser constructor. If @args contains the key-value pair "(canonicalize => 1)", literal value canonicalization will be attempted during parsing with warnings being emitted for invalid lexical forms for recognized datatypes. "parse_url_into_model ( $url, $model [, %args] )" Retrieves the content from $url and attempts to parse the resulting RDF into $model using a parser chosen by the associated content media type. If %args contains a 'content_cb' key with a CODE reference value, that callback function will be called after a successful response as: $content_cb->( $url, $content, $http_response_object ) "parse_into_model ( $base_uri, $data, $model [, context => $context] )" Parses the $data, using the given $base_uri. For each RDF statement parsed, will call "$model->add_statement( $statement )". "parse_file_into_model ( $base_uri, $fh, $model [, context => $context] )" Parses all data read from the filehandle or file $fh, using the given $base_uri. For each RDF statement parsed, will call "$model->add_statement( $statement )". "parse_file ( $base_uri, $fh, $handler )" Parses all data read from the filehandle or file $fh, using the given $base_uri. If $fh is a filename, this method can guess the associated parse. For each RDF statement parses $handler is called. "parse ( $base_uri, $rdf, &handler )" "new_bnode_prefix ()" Returns a new prefix to be used in the construction of blank node identifiers. If either Data::UUID or UUID::Tiny are available, they are used to construct a globally unique bnode prefix. Otherwise, an empty string is returned. BUGS
Please report any bugs or feature requests to through the GitHub web interface at <https://github.com/kasei/perlrdf/issues>. AUTHOR
Gregory Todd Williams "<gwilliams@cpan.org>" COPYRIGHT
Copyright (c) 2006-2012 Gregory Todd Williams. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. perl v5.14.2 2012-06-29 RDF::Trine::Parser(3pm)
All times are GMT -4. The time now is 04:53 AM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy