Home > OS >  How to separate two different data in a JSON array with vertical pipeline as separator using python
How to separate two different data in a JSON array with vertical pipeline as separator using python

Time:11-11

Below is my sample json string in 2 different lines

{""creditNoteId"":""BSA11130181-S7"",""creditNoteUrl"":""www.twitir.com""}
{""creditNoteId"":""BSA11130181-S8"",""creditNoteUrl"":""www.googol.com""}|{""creditNoteId"":""BSA11130181-S9"",""creditNoteUrl"":""www.fesbuuk.com""}

I am not having issue with the first line but in the second line, which is having vertical pipeline as separator, it is giving me error

I want to print them like below

BSA11130181-S7 www.twitir.com
BSA11130181-S8 www.googol.com
BSA11130181-S9 www.fesbuuk.com

Currently I am having below error

raise JSONDecodeError("Extra data", s, end)

Using Below python code

        a = credit_note
        y = json.loads(a)
        for x in y:
          print(y["creditNoteId"], y["creditNoteUrl"])
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:


import json

d1 = '{"creditNoteId":"BSA11130181-S7","creditNoteUrl":"www.twitir.com"}'
d2 = '{"creditNoteId":"BSA11130181-S8","creditNoteUrl":"www.googol.com"}|{"creditNoteId":"BSA11130181-S9","creditNoteUrl":"www.fesbuuk.com"}'
d2 = d2.replace('|',',') # point 1
d3 = '[{'   d2[1:-1:]   '}]'  # point 2
y = json.loads(d3)
for x in y:
    print(x["creditNoteId"], x["creditNoteUrl"])

This code will work for you..

  1. replace | with ,
  2. replace first and last curly brace with [{ and ]} to make it a valid JSON object.
  3. Also make sure that d1 and d2 is string as posted in code above as json.loads expect a string argument.
  • Related