Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9247689
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T09:47:39+00:00 2026-06-18T09:47:39+00:00

I have a data in format: id1 id2 value Something like 1 234 0.2

  • 0

I have a data in format:

id1 id2 value
Something like

1   234  0.2
1   235  0.1

and so on.
I want to convert it in json format:

{
  "nodes": [ {"name":"1"},  #first element
             {"name":"234"}, #second element
             {"name":"235"} #third element
             ] ,
   "links":[{"source":1,"target":2,"value":0.2},
             {"source":1,"target":3,"value":0.1}
           ]
}

So, from the original data to above format.. the nodes contain all the set of (distinct) names present in the original data and the links are basically the line number of source and target in the values list returned by nodes.
For example:

   1 234 0.2

1 is in the first element in the list of values holded by the key “nodes”
234 is the second element in the list of values holded by the key “nodes”

Hence the link dictionary is {“source”:1,”target”:2,”value”:0.2}

How do i do this efficiently in python.. I am sure there should be better way than what I am doing which is so messy 🙁
Here is what I am doing
from collections import defaultdict

def open_file(filename,output=None):
    f = open(filename,"r")
    offset = 3429
    data_dict = {}
    node_list = []
    node_dict = {}
    link_list = []
    num_lines = 0
    line_ids = []
    for line in f:
        line = line.strip()
        tokens = line.split()
        mod_wid  = int(tokens[1]) + offset


        if not node_dict.has_key(tokens[0]):
            d = {"name": tokens[0],"group":1}
            node_list.append(d)
            node_dict[tokens[0]] = True
            line_ids.append(tokens[0])
        if not node_dict.has_key(mod_wid):
            d = {"name": str(mod_wid),"group":1}
            node_list.append(d)
            node_dict[mod_wid] = True
            line_ids.append(mod_wid)


        link_d = {"source": line_ids.index(tokens[0]),"target":line_ids.index(mod_wid),"value":tokens[2]}
        link_list.append(link_d)
        if num_lines > 10000:
            break
        num_lines +=1


    data_dict = {"nodes":node_list, "links":link_list}

    print "{\n"
    for k,v in data_dict.items():
        print  '"'+k +'"' +":\n [ \n " 
        for each_v in v:
            print each_v ,","
        print "\n],"
    print "}"

open_file("lda_input.tsv")
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T09:47:40+00:00Added an answer on June 18, 2026 at 9:47 am

    Don’t construct the JSON manually. Make it out of an existing Python object with the json module:

    def parse(data):
        nodes = set()
        links = set()
    
        for line in data.split('\n'):
            fields = line.split()
    
            id1, id2 = map(int, fields[:2])
            value = float(fields[2])
    
            nodes.update((id1, id2))
            links.add((id1, id2, value))
    
        return {
            'nodes': [{
                'name': node
            } for node in nodes],
            'links': [{
                'source': link[0],
                'target': link[1],
                'value': link[2]
            } for link in links]
        }
    

    Now, you can use json.dumps to get a string:

    >>> import json
    >>> data = '1   234  0.2\n1   235  0.1'
    >>> parsed = parse(data)
    >>> parsed
        {'links': [{'source': 1, 'target': 235, 'value': 0.1},
      {'source': 1, 'target': 234, 'value': 0.2}],
     'nodes': [{'name': 1}, {'name': 234}, {'name': 235}]}
    >>> json.dumps(parsed)
        '{"nodes": [{"name": 1}, {"name": 234}, {"name": 235}], "links": [{"source": 1, "target": 235, "value": 0.1}, {"source": 1, "target": 234, "value": 0.2}]}'
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a data in Microsoft SQL server with the following format: id1 id2
I am merging business databases. So I have data like id1 id2 id1 id2
In controller code, I have data in json format data = { 1: {assetId:1,status:true},
I have a XML file with the following data format: <net NetName=abc attr1=123 attr2=234
I want to dynamically append data received via an url in JSOn format to
I have a large data set coming back in JSON format such that I
I need to take a data.frame in the format of: id1 id2 mean start
Data roughly in the format A B C ID1 ID2 0.5 ID1 ID3 0.7
I have a big JSON object with lots of data in it. I want
I have some data in JSON format in a text file as below. I

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.