将Python对象转换为JSON字符串

时间:2016-09-27 02:32:45

标签: python json

我一直在研究这个机器人,它接受了twitter api并将其带入我的数据库。在考虑我使用1个超出限制要求的时间之前,我在抓一条推文之前并没有效率。所以我决定抓住150个结果。我得到了这些结果:

jakes_mac:SomeCode jake$ cap staging deploy INFO [hkdgad21] Running /usr/bin/env mkdir -p /tmp/somecode/ as jake@example.com DEBUG [hkdgad21] Command: /usr/bin/env mkdir -p /tmp/somecode/ jake@example.com's password: INFO [hkdgad21] Finished in 5.166 seconds with exit status 0 (successful). DEBUG Uploading /tmp/somecode/git-ssh.sh 0.0% INFO Uploading /tmp/somecode/git-ssh.sh 100.0% INFO [xyz20312] Running /usr/bin/env chmod +x /tmp/somecode/git-ssh.sh as jake@example.com DEBUG [xyz20312] Command: /usr/bin/env chmod +x /tmp/somecode/git-ssh.sh INFO [xyz20312] Finished in 0.240 seconds with exit status 0 (successful). INFO [abcdef01] Running /usr/bin/env git ls-remote --heads git@github.com:SomeUser/SomeCode.git as jake@example.com DEBUG [abcdef01] Command: ( GIT_ASKPASS=/bin/echo GIT_SSH=/tmp/somecode/git-ssh.sh /usr/bin/env git ls-remote --heads git@github.com:SomeUser/SomeCode.git ) DEBUG [abcdef01] Permission denied (publickey). DEBUG [abcdef01] fatal: Could not read from remote repository. DEBUG [abcdef01] DEBUG [abcdef01] Please make sure you have the correct access rights DEBUG [abcdef01] and the repository exists. (Backtrace restricted to imported tasks) cap aborted! SSHKit::Runner::ExecuteError: Exception while executing as jake@example.com: git exit status: 128 git stdout: Nothing written git stderr: Permission denied (publickey). fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. SSHKit::Command::Failed: git exit status: 128 git stdout: Nothing written git stderr: Permission denied (publickey). fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. Tasks: TOP => git:check (See full trace by running task with --trace) The deploy has failed with an error: Exception while executing as jake@example.com: git exit status: 128 git stdout: Nothing written git stderr: Permission denied (publickey). fatal: Could not read from remote repository.

我得到了大约150个。是否有一个库可以将其转换为JSON?

3 个答案:

答案 0 :(得分:3)

如果您使用的是2.6+,那么您可以使用捆绑的库(docs),只需:

> Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result,
> boolean given in D:\Xampp\htdocs\student\announcement.php on line 8
> 
> Notice: Undefined variable: data in
> D:\Xampp\htdocs\student\announcement.php on line 12 null

我们经常使用这个快速的API端点,您只需要注意在您尝试序列化的对象中使用函数或复杂的嵌套,它是可配置的(因此您可以跳过字段,自定义某些输出,等)但很快就会变得混乱。

答案 1 :(得分:1)

是的,快速Google搜索会显示json模块。

import json

# instead of an empty list, create a list of dict objects 
# representing the statues as you'd like to see them in JSON.
statuses = { 'statuses': [] } 

with open('file.json', 'w') as f:
    f.write(json.dumps(statuses).encode('utf-8'))

答案 2 :(得分:0)

import json
jsondata = json.dumps(TwitterStatusObject.__dict__)