需要帮助json与python outtping

时间:2022-08-26 11:23:59

Im in need of help outputting the json key with python. I tried to output the name "carl".

我需要帮助输出与python的json密钥。我试图输出名称“carl”。

Python code :

Python代码:

 from json import loads
 import json,urllib2

class yomamma:
  def __init__(self):
      url = urlopen('http://localhost/name.php').read()
      name = loads(url)
      print "Hello" (name)

Php code (for the json which i made):

PHP代码(我做的json):

<?php
$arr = array('person_one'=>"Carl", 'person_two'=>"jack");
echo json_encode($arr);

the output of the php is : {"person_one":"Carl","person_two":"jack"}

php的输出是:{“person_one”:“Carl”,“person_two”:“jack”}

2 个解决方案

#1


1  

I'll just assume the PHP code works correctly, I don't know PHP very well.

我只是假设PHP代码正常工作,我不太了解PHP。

On the client, I recommend using requests (installable through pip install requests):

在客户端,我建议使用请求(可通过pip安装请求安装):

import requests

r = requests.get('http://localhost/name.php')
data = r.json()
print data['person_one']

The .json method returns a Python dictionary.

.json方法返回Python字典。

Taking a closer look at your code, it seems you're trying to concatenate two strings by just writing them next to eachother. Instead, use either the concatenation operator (+):

仔细看看你的代码,看起来你正试图通过将它们写在彼此旁边来连接两个字符串。相反,使用连接运算符(+):

print "Hello" + data['person_one']

Alternatively, you can use the string formatting functionality:

或者,您可以使用字符串格式化功能:

print "Hello {}".format(data['person_one'])

Or even fancier (but maybe a bit complex to understand for the start):

甚至更高级(但开始时可能有点复杂):

r = requests.get('http://localhost/name.php')
print "Hello {person_one}".format(**r.json())

#2


0  

try this:

import json
person_data = json.loads(url)
print "Hello {}".format(person_data["person_one"])

#1


1  

I'll just assume the PHP code works correctly, I don't know PHP very well.

我只是假设PHP代码正常工作,我不太了解PHP。

On the client, I recommend using requests (installable through pip install requests):

在客户端,我建议使用请求(可通过pip安装请求安装):

import requests

r = requests.get('http://localhost/name.php')
data = r.json()
print data['person_one']

The .json method returns a Python dictionary.

.json方法返回Python字典。

Taking a closer look at your code, it seems you're trying to concatenate two strings by just writing them next to eachother. Instead, use either the concatenation operator (+):

仔细看看你的代码,看起来你正试图通过将它们写在彼此旁边来连接两个字符串。相反,使用连接运算符(+):

print "Hello" + data['person_one']

Alternatively, you can use the string formatting functionality:

或者,您可以使用字符串格式化功能:

print "Hello {}".format(data['person_one'])

Or even fancier (but maybe a bit complex to understand for the start):

甚至更高级(但开始时可能有点复杂):

r = requests.get('http://localhost/name.php')
print "Hello {person_one}".format(**r.json())

#2


0  

try this:

import json
person_data = json.loads(url)
print "Hello {}".format(person_data["person_one"])