0

i have a problems with writing a list to JSON file, here s code:

import numpy as np
import json

filename = "sub-01_task-rest_bold.json"
with open(filename, 'r') as f:
    niiMeta = json.load(f)

rTime = niiMeta.get("RepetitionTime")
nSlices = niiMeta.get("dcmmeta_shape")
imType = niiMeta.get("ImageType")


def numberofslices(n):
    if "EPI" in imType and len(nSlices) == 4:
        h = n[2]
        return h
    else:
        return 0


def checktr(t):
    if t >= 1000:
        k = t*0.001
        return k
    else:
        return t


def slicetime(tr, n):

    tr = checktr(tr)
    n = numberofslices(n)
    lastslice = tr - tr/n
    esti = np.linspace(0, lastslice, n)

    return esti


addstc = slicetime(rTime, nSlices).tolist()
niiMeta["SliceTiming "] = addstc


with open(filename, 'w') as f:
    json.dump(niiMeta, f, indent=4)

It work and creates new key with list, but it differs from original file: ORIGINAL:with horizontal line

OUTPUT:[with vertical line][2]

As you can see it have an tabs in list. Please help me to remove it.

Relyativist
  • 56
  • 1
  • 11
  • Could you explain what is tabs in list? – Xnkr Aug 21 '18 at 17:16
  • 2
    Why does it matter? It's valid JSON either way. – ShadowRanger Aug 21 '18 at 17:16
  • 1
    There's no way to force JSON to follow exactly the same format as some input. There are limited ways to control the JSON pretty-printing (you can see the options [in the docs](https://docs.python.org/3/library/json.html#json.dump)), and beyond that, the only way to control things more finely is to subclass and override `JSONEncoder` (or maybe find a third-party library… but the one most people use, `simplejson`, has basically the same options). – abarnert Aug 21 '18 at 17:18
  • 1
    Having `indent=4` will always indent all containers with 4 spaces. You can't get the same formatting as in your original file out of the box with `json` from the standard library. – AKX Aug 21 '18 at 17:18
  • Possible duplicate: https://stackoverflow.com/a/13252112/7570485 – Xnkr Aug 21 '18 at 17:25
  • @ShadowRanger Thanks for qiustion, It s confused me a little, cause size of Original and output differs 3 times. – Relyativist Aug 21 '18 at 17:25

0 Answers0