2016-07-29 139 views
1

我需要帮助输出与python json键。我试图输出名字“carl”。需要帮助输出json与python

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代码(用于JSON我制造):

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

在PHP的输出为: { “person_one”: “卡尔”,” person_two“:”jack“}

回答

1

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

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

import requests 

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

.json方法返回Python字典。

仔细看看你的代码,似乎你试图连接两个字符串,只是把它们写在海誓山盟旁边。相反,使用连接符(+):

print "Hello" + data['person_one'] 

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

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

或者更炫(但也许有点复杂,难于理解的开始) :

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

谢谢,虐待现在:) –

0

试试这个:

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