Skipping ahead to your current and desired outputs:
{'indicators': [{'value': '192.91.72.201', 'type': 'ip'}]} {'providers': [{'provider': "['Bkav', 'CMC Threat Intelligence', 'CMC sarah ']", 'verdict': "['clean', 'legs', 'hate']", 'score': "['harmless', 'harmless', 'sarah']"}, {...}]}
{'indicators': [{'value': '192.91.72.101', 'type': 'ip'}]} {'providers': [{'provider': "['Bkav', 'CMC Threat Intelligence', 'CMC sarah ']", 'verdict': "['clean', 'legs', 'hate']", 'score': "['harmless', 'harmless', 'sarah']"}, {...}]}
Desired:
{
"providers":\[
{
"provider":"['Bkav']",
"verdict":"['clean']",
"score":"['harmless']"
},
{
"provider":"['CMC Threat Intelligence']",
"verdict":"['clean']",
"score":"['harmless']"
},
{
"provider":"['CMC sarah']",
"verdict":"['hate']",
"score":"['harmless']"
]
}
Your desired output is JSON format. But your current output isn’t
JSON. It is actually Python dict
s and list
s from this print()
call:
print(out_json,out_json1)
So what’s going on is a little confusing, because they’re quite similar.
It isn’t helped by the fact that you’ve named your variables out_json
and out_json1
and similar. They’re not JSON, they’re plain old
Python dict
s. But the names will be misleading you.
So let’s hardwire a small example:
import json
d = {'a': 1, 'b': [3,4,5]}
print(d)
print(json.dumps(d))
Let’s dissect that:
import json
Import the json
module, for obvious reasons.
d = {'a': 1, 'b': [3,4,5]}
Define a small dict
, with an entry with key 'a'
whose value is the
value 1
and an entry with key ‘b’ whose value is the list [3,4,5]
.
Now, the dict
isn’t “in JSON format”, or any format really. It is just
a data structure. But the Python syntax for writing out such a dict
directly looks a bit JSONish:
{'a': 1, 'b': [3,4,5]}
If you wrote that value in (JSON format)[JSON - Wikipedia]
you might write:
{"a": 1, "b": [3,4,5]}
and the most obvious difference is the quote marks. But JSON is
JavaScript compatible. Anyway, JSON’s a fiel format for
reading/writing values. The variable d
itself isn’t “in JSON format”
or “Python syntax”; it is just a value.
Let’s get to the output:
print(d)
When you call print()
, it converts each of its arguments to a string,
and writes the strings with a space between each string. The variable
d
is a dict
, and str(d)
is that same as repr(d)
which is the
Python syntax for the dict
. Thus the Pythonesque output.
Now the second print()
:
print(json.dumps(d))
When that runs, it prints this:
{"a": 1, "b": [3, 4, 5]}
That’s because json.dumps(d)
returns a string with the value in JSON
format. ANd print converts that string into… exactly the same string,
because it’s already a string.
You want line breaks in your output. Looking at the documentation for
json.dumps
here:
you’ll see it has a separators
parameter. Have a fiddle with supplying
values for that parameter in your json.dumps()
call and see how things
look.
Cheers,
Cameron Simpson cs@cskk.id.au