scripting scripting - 11 days ago 7
JSON Question

using python - grab only particular values from key:value pairs in parsed JSON

I am trying to extract particular data from a JSON file. Here is my code.

jsonurl = http://localhost:8080/test.json
a = urllib2.urlopen(jsonurl).read()
b = json.loads(a)
for x, y in b.iteritems():
print x, y


here is my json

{
"abc": [
"build=1.0.44.0",
"proxy=none"
],
"xyz": [
"proxy=https",
"build=1.0.127.0"
],
"alfa": [
"build=1.0.118.0",
"proxy=none"
],
"beta": [
"proxy=http"
"build=1.0.20.0"
]
}


I am getting all both the key and value from the json but i only need to extract key: value of (build =).
my desired output is
abc:1.0.44.0
xyz:1.0.127.0 ....etc I tried many options but couldn't get desired results.

Answer
jsonurl = http://localhost:8080/test.json
a = urllib2.urlopen(jsonurl).read()
b = json.loads(a)
for x, y in b.iteritems():
    print x, y

Prints each key/value in the dictionary. Each of your values is actually a list, so to access a list item, you would need to use the proper syntax.

for x, y in b.iteritems():
    print x, y, y[0]

Will show your key, value, and value[0].

Now, identify which element of the list contains the build= string:

> my_list = ["proxy=https", "build=1.0.127.0"]
> build_str = [i for i in my_list if 'build=' in i][0]
> build_str
build=1.0.127.0

From there, you can evolve your program to parse the string. To parse a string as you are asking, I usually look for an easy 'split' delimiter. In this case, the = stands out. Split will take a string and create a list with breaks at every delimiter.

> my_str_as_a_list = "build=1.0.20.0".split('=')
> my_str_as_a_list
['build', '1.0.20.0']
> my_str_as_a_list[1]
1.0.20.0

Now, apply this concept to your for loop:

for key, value in b.iteritems():
    my_str = [i for i in value if 'build=' in i][0]
    v = my_str.split('=')[1]
    print '{}:{}'.format(key, v)

I am not sure if you want an output in the form of a dictionary/string/list based on your question, but you should be able to get there easily with the provided answers.