1

I'm trying to read a json file in python and I want to break a long value into multiples lines to make it easier to read it.

e.g JSON file:

mem's value is too long, so I'd like to make it multiple lines.

{
    "resource":{
        "cpu": ["host, usage_system, usage_user, usage_iowait", "1=1"],
        "mem": ["host, active/(1024*1024) as active, available/(1024*1024) as available, available_percent, buffered/(1024*1024) as buffered, cached/(1024*1024) as cached, swap_cached/(1024*1024) swap_cached, swap_total/(1024*1024) swap_total, total/(1024*1024) mem_total, used/(1024*1024) mem_used", "1=1"],
        "net": ["host, bytes_recv, bytes_sent, packets_recv, packets_sent", "1=1 and interface != 'all'"]
    }
}

I want to make the value like below.

{ "resource":{
                "cpu": ["host, usage_system, usage_user, usage_iowait", "1=1"],
                "mem": ["host, active/(1024*1024) as active, available/(1024*1024) as available, 
    available_percent, buffered/(1024*1024) as buffered, 
    cached/(1024*1024) as cached, swap_cached/(1024*1024) swap_cached, 
    swap_total/(1024*1024) swap_total, 
    total/(1024*1024) mem_total, used/(1024*1024) mem_used", "1=1"],
                "net": ["host, bytes_recv, bytes_sent, packets_recv, packets_sent", "1=1 and interface != 'all'"]
            }
        }

Thanks!

mahmoudafer
  • 1,139
  • 3
  • 14
  • 30
Ben
  • 45
  • 1
  • 1
  • 6
  • 1
    I don't think there's a good way to do this. You can write new line characters into the data but then that can cause issues (it might work on one platform, language, etc, but not another). Why not set your editor to wrap the lines when dealing with json files? – moorej Jul 16 '19 at 02:14
  • @moorej Yes you're right. I couldn't think of it. I've turned wrap function on my IDE. Thanks a lot!! – Ben Jul 16 '19 at 02:59

1 Answers1

0

ok, so you are probably going to want to make a list of strings in json, then combine them with "".join(). For example, json.json

{
    "multiline": [
        "this is a re",
        "ally long st",
        "ring, so I n",
        "eed to make ",
        "it one line"
    ]
}

multiline.py

import json
with open("json.json", "r") as jsonfile:
    stringlist = json.loads(jsonfile.read())["multiline"]
    result = "".join(stringlist)
    print(result)
MaisyDoge13
  • 154
  • 1
  • 3
  • 14