2

I am trying to load a simple json which is,

[
  {
    "positions": [
      {
        "title": "a",
        "is-current": true,
        "company-name": "a"
      }
    ],
    "public-profile-url": "\/pub\/ademar-b\/20\/22b\/842",
    "location": "Irati Area, Brazil",
    "first-name": "Ademar",
    "num-connections": "4",
    "last-name": "B",
    "industry": "Government Administration"
  },
  {
    "positions": [
      {
        "title": "Messenger",
        "is-current": true,
        "company-name": "YAA Croup"
      },
      {
        "title": "Messenger",
        "is-current": true,
        "company-name": "YAA Croup"
      }
    ],
    "public-profile-url": "\/pub\/adememb-b\/41\/7a8\/171",
    "location": "Ethiopia",
    "first-name": "adememb",
    "num-connections": "0",
    "last-name": "B",
    "industry": "Wholesale"
  }
]

My task is to load the json, clean some entries and then dump it to file. But my following simple code is giving error:

    profiles=json.load(fin)
    json.dumps(outfile,profiles)

I am not able to understand as why this simple thing is not working, where I am just loading and dumping same json?

0

1 Answer 1

5

You are using the wrong function; you are trying to turn the file object into a JSON string:

>>> json.dumps(open('/tmp/demo.json', 'w'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/json/__init__.py", line 243, in dumps
    return _default_encoder.encode(obj)
  File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/json/encoder.py", line 207, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/json/encoder.py", line 270, in iterencode
    return _iterencode(o, 0)
  File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/json/encoder.py", line 184, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <open file '/tmp/demo.json', mode 'w' at 0x1006576f0> is not JSON serializable

You want to use json.dump() here (no s), but :

json.dump(profiles, outfile)

The object to serialise comes first, the file object second.

Sign up to request clarification or add additional context in comments.

2 Comments

For some odd reason, this answer is accepted even though OP pointed out that using dump instead of dumps makes no difference. This was 6 years ago, I guess OP found an answer eventually.
@speyck: it is accepted because the OP admitted that they used json.dump() wrong in the comments here, since deleted. I've removed their later edit, since it doesn't apply here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.