Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
json to ndjson
#1
I have a output from request.get it is something like this
actual output is long and multiple of this line.

[{"a":1,"b":2,"c":3},{"x":4,"y":5,"z":6}]

i want this to convert to something like this

{"a":1,"b":2,"c":3}
{"x":4,"y":5,"z":6}

how do I do this?
Reply
#2
Do you want to write your own? You could just install ndjson

import json
import ndjson

input = '[{"a":1,"b":2,"c":3},{"x":4,"y":5,"z":6}]'
data = json.loads(input)
output = ndjson.dumps(data)
print(output)
Output:
{"a": 1, "b": 2, "c": 3} {"x": 4, "y": 5, "z": 6}
Reply
#3
Instead of
output = ndjson.dumps(data)
print(output)
use:
print(ndjson.dumps(data))
Reply
#4
@macfanpl: And why should they do that? If they have the output from ndjson.dumps() in a variable, they can use it later, e.g. writing to a file. they can always print that variable.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
Thank you both of you

This is how my code is
response = requests.get(url, params=params, auth=('user', 'pass'))
#
print (response.headers['content-type'])
--> this says 'application/json; charset=utf-8'

json_response = response.json()
print (response.json())
### out put of this is like this
{'page': 1, 'per_page': 20, 'total': 9, 'saved_objects': [{'type': 'dashboard',................ 'version': 'WzM5OTEsM10='}]}

data = json.loads(json_response)
print (ndjson.dumps(data))
this last two line give me this error
File "export_output.py", line 35, in <module>
data = json.loads(json_response)
File "/usr/lib64/python3.6/json/__init__.py", line 348, in loads
'not {!r}'.format(s.__class__.__name__))
TypeError: the JSON object must be str, bytes or bytearray, not 'dict'


This tells me this is not json string

ignore above it works now. Thank you guys.
it was typo on my part.

here is what my final code is
Actually found out that output of my request.get was ndjson already.
then use your logic for seperate out lines.

items = response.json(cls=ndjson.Decoder)
print (items)
print()
output = ndjson.dumps(items)
print (output)
Reply
#6
(May-22-2020, 08:01 AM)buran Wrote: @macfanpl: And why should they do that? If they have the output from ndjson.dumps() in a variable, they can use it later, e.g. writing to a file. they can always print that variable.

First: learn to cope with being defeated.
Second: Learn to code resource-wise
Three: Thats perfect example of how "friendly" you all are.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020