0

I want to check is "Code":"A" avaiable in json file. I already searching on internet and read many QA in stackoverflow but it does not help me. Could anyone show me how to do it?

with open(dummyJson_url):
    dataList = json.load(open(dummyJson_url))

test = json.loads("""{"Code":"A"}""")

racksLocation = dataList["Test"]

for i in range(len(racksLocation)):

    newLoc = dataList["Test"][i]

    if sorted(test.items()) in sorted(newLoc.items()):
        print("Yes")
        break

    else:
        print("No")

and here is my json:

{
    "Test": [
        {
            "Code":"A",
            "Buyer": []
        },
        {
            "Code":"B",
            "New": []
        },
        {
            "Code":"C",
            "Racks": []
        },
        {
            "Code":"D",
            "Baru": []
        }
    ]
}
1
  • What's the error are you getting? Commented Oct 4, 2019 at 7:53

5 Answers 5

1

There is a very simple problem:

>>> print(sorted(test.items()))
[('Code', 'A')] #a list with 1 item(tuple) in it

>>> print(sorted(newLoc.items()))
[('Buyer', []), ('Code', 'A')] #a list with 2 tuples

So when you are trying this:

if sorted(test.items()) in sorted(newLoc.items()):
   ...

the condition fails because [('Code', 'A')] is NOT in [('Buyer', []), ('Code', 'A')] but ('Code', 'A') is! (notice the lack of list brackets here)

All you need to do is access the first(and only) element in [('Code', 'A')] (which is sorted(test.items())[0])

This is all you need to do using just your approach if you prefer to stick with it(which could improve but I wont get into it):

with open(dummyJson_url):
    dataList = json.load(open(dummyJson_url))

test = json.loads("""{"Code":"A"}""")

racksLocation = dataList["Test"]

for i in range(len(racksLocation)):

    newLoc = dataList["Test"][i]

    if sorted(test.items())[0] in sorted(newLoc.items()): #you are now checking the first element inside the list
        print("Yes")
        break

    else:
        print("No")
Sign up to request clarification or add additional context in comments.

Comments

0

Simplified your code:

with open(dummyJson_url):
    dataList = json.load(open(dummyJson_url))

for item in datalist['Test']:
    if 'Code' in item and item['Code'] == "A":
        print 'yes'
        break
    else:
        print 'no'

Comments

0

When you do json.loads(json_string) it gives you dictionary if you get for example json_data={"a":1} if you do json_data.get("a") it will give you value 1 if present or None so simply you can check you can make a resulable function for this

 def check_in_json(jsondata,key,value):
       for data in jsondata:
           if data.get(key) == value:
              return True
       return False

And call it like

json_data={
    "Test": [
        {
            "Code":"A",
            "Buyer": []
        },
        {
            "Code":"B",
            "New": []
        },
        {
            "Code":"C",
            "Racks": []
        },
        {
            "Code":"D",
            "Baru": []
        }
    ]
}

check_in_json(json_data["Test"],"Code","A") #you will get True if found else false

Comments

0

Going with your approach, Try below code:

with open(dummyJson_url):
    dataList = json.load(open(dummyJson_url))

test = {"Code":"A"}

for data in dataList["Test"]:
    if test.items() <= data.items():   # In dict, .items() would give you the set type which can be compared.
        print("Yes")
        break
    else:
        print("No")

Hope this helps!

Comments

0

JSONObject class has a method named "has":

http://developer.android.com/reference/org/json/JSONObject.html#has(java.lang.String)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.