简体   繁体   English

Python JSON解析,检查值是否以某些内容开头

[英]Python JSON parsing, check if value starts with something

I am reading in JSON from a URL and am running into some issues manipulating the data. 我正在从URL中读取JSON,并且在处理数据时遇到了一些问题。

JSON is as follows: JSON如下:

{
  "Id": "1234,
  "something": "{..."
}

I read in the JSON from a url as follows, which works fine. 我从URL读取JSON,如下所示,效果很好。

response = urllib.urlopen(url)
data = json.loads(response.read())

Now what I want to do is whenever the value of "something" starts with '{', append "Id" to a list. 现在,我想做的就是每当“ something”的值以“ {”开头时,将“ Id”附加到列表中。 Here is what I have: 这是我所拥有的:

for x in data:
    if x.get("something").startswith('{'):
        do something...

I get the following error: 我收到以下错误:

if x.get("something").startswith('{'):  

AttributeError: 'NoneType' object has no attribute 'startswith' AttributeError:'NoneType'对象没有属性'startswith'

Anyway I can get this to work, or other suggestions on how to accomplish this? 无论如何,我可以使它起作用,或者关于如何完成此操作的其他建议?

You are on the right track.. 您在正确的轨道上..

First you need to check that "something" exists, otherwise your code will turn "None" which is why you are getting an error, you could try the following to ensure that this is the case: 首先,您需要检查“东西”是否存在,否则您的代码将变成"None" ,这就是为什么您会收到错误消息,您可以尝试以下操作以确保是这种情况:

for key, value in data.items():
    if key == "something":
        if value.startswith('{'):
            # do something...

I think you only need this part : 我认为您只需要这部分:

if data.get("something").startswith("{"):

because its a dict , you can get the dict value by calling the key with the dict name. 因为它是dict,所以您可以通过使用dict名称调用键来获取dict值。 No need to loop. 无需循环。

While you looping it will loop through the keys.If you want to do it in your way you can do like this : 在循环时,它会循环遍历各个键。如果您想以自己的方式进行操作,可以这样做:

for x, y in data.items():
    if x=="something" and y.startswith("{"):
          do what you want...
good_items = ["""something""" for k in data if k.startswith('{')]

Instead of """something""", you could put a method call to a function taking a single argument (the individual key). 代替“”“ something”“”,您可以对带有单个参数(单个键)的函数进行方法调用。 This will yield a list of items from data for which the condition matches. 这将根据条件匹配的数据生成项目列表。 Hope that helps... 希望有帮助...

data is a dictionary, and "something" is a key in the dictionary that is or is not present. data是字典,“ something”是字典中存在或不存在的键。 The following code checks if the key is present (then it extracts the value associated with the code, and checks if the value starts with a "{"); 下面的代码检查该键是否存在(然后提取与该代码关联的值,并检查该值是否以“ {”开头); or not (then it replaces the value with an empty string that does not start with a "{"): 是否(然后用一个不以“ {”开头的空字符串替换该值):

if data.get("something","").startswith("{"): ...

If the key is definitely present, the solution is even simpler: 如果肯定存在密钥,则解决方案甚至更简单:

if data["something"].startswith("{"): ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM