将JSON响应从Ruby映射到Python

时间:2018-06-15 18:02:16

标签: python json ruby python-3.x code-conversion

[编辑]:对不起,我第一次没有详细解释,因为我想为自己解决剩下的问题,但我最终让自己感到困惑 < / p>

我有一个小问题。 我想利用网站的API JSON响应

{
    "Class": {
        "Id": 1948237,
        "family": "nature",
        "Timestamp": 941439
    },
    "Subtitles":    [
      {
        "Id":151398,
        "Content":"Tree",
        "Language":"en"
      },
      {
        "Id":151399,
        "Content":"Bush,
        "Language":"en"
      }
    ]
}

所以我想用每行字幕的组合字符串打印网址,并用换行符分隔

我设法在Ruby中这样做:

def get_word
    r = HTTParty.get('https://example.com/api/new')
# Check if the request had a valid response.
    if r.code == 200
        json = r.parsed_response
        # Extract the family and timestamp from the API response.
        _, family, timestamp = json["Class"].values

        # Build a proper URL
        image_url = "https://example.com/image/" + family + "/" + timestamp.to_s

        # Combine each line of subtitles into one string, seperated by newlines.
        word = json["Subtitles"].map{|subtitle| subtitle["Content"]}.join("\n")

        return image_url, word
    end
end

但是现在我需要将它移植到python中,因为我在python中很糟糕,我似乎无法弄清楚它。

我使用的是请求而不是HTTParty,因为我认为它是最好的等价物。 我试过这样做:

def get_word():
  r = requests.request('GET', 'https://example.com/api/new')
  if r.status_code == 200:
      json = requests.Response
      # [DOESN'T WORK] Extract the family and timestamp from the API response. 
      _, family, timestamp = json["Class"].values

      # Build a proper URL
      image_url = "https://example.com/image/" + family + "/" + timestamp.to_s

      # Combine each line of subtitles into one string, seperated by newlines.
      word = "\n".join(subtitle["Content"] for subtitle in json["Subtitles"])
      print (image_url + '\n' + word)

get_word()

但是我在提取JSON响应和组合行

时遇到困难

2 个答案:

答案 0 :(得分:2)

Pythonic的方法是使用列表理解。

<?php

    include 'ConnectionInfo.php';
    try
    {
      $dsn="sqlsrv:Server=$Servername;Database=$Database";
      $pdo = new PDO($dsn,$Username,$Password);
      $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    }
    catch (PDOException $e)
    {

      echo "Connection to database failed: " . $e->getMessage();

    }

    ?>

答案 1 :(得分:1)

您可能需要将传入的json转换为python词典

假设这是您的回复

  

response = {“字幕”:...}

#convert to dict
import json
json_data = json.loads(response)
# print content
for a_subtitle in response['Subtitles']:
    print(a_subtitle['content'])

# extract family and timestamp
family = json_data["Class"]["family"]
timestamp = json_data["Class"]["Timestamp"]
image_url = "https://example.com/image/" + family + "/" + str(timestamp)