Am trying to extract command line arguments passed in python
cmdargs = str(sys.argv)
print cmdargs
it prints
['E:/omation.py', '{"command":"sel_media","value":"5X7_phot
o_paper.png"},{"command":"tray","value":"4X6_photo_paper.png"}']
from this how can i extract command and values .
i dont knoe how to loop this array and get the commnd and value values.plese help
Note: i also want to discard the first value 'E:/omation.py'
You can use Python utils to parse json strings:
import json
examples = json.loads('['+cmdargs[1]+']')
The first import loads json utilities for python. Then, you can parse a json string into a Python dictionary by using json.loads. In the example, I have parsed one of your json strings into a python dictionary. Remember to add '[' and ']' to convert your string to a valid json array. Then, you can get a command and a value like :
print(examples[0]['command'])
print(examples[0]['value' ])
The example you give shows two json objects in the second element of the list cmdargs. Probably the easiest way to capture that case would be to enclose that second argument in square braces, which would make it legal JSON, then loop through the resulting list:
import json
a = json.loads('['+cmdargs[1]+']')
for p in a:
print "command is ", p['command']
print "value is ", p['value']
This is specific to the example you showed, you may need to make it more robust for your purposes.
Your input is not valid JSON. You must find a way to pass the arguments as separate, valid JSON objects. Then you can do this:
# j.py
import json
import sys
print(sys.argv)
for arg in sys.argv[1:]:
j = json.loads(arg)
print(j.get("command"))
print(j.get("value"))
Usage could be:
$ python3 j.py '{"command":"sel_media","value":"5X7_photo_paper.png"}' '{"command":"tray","value":"4X6_photo_paper.png"}'
['j.py', '{"command":"sel_media","value":"5X7_photo_paper.png"}', '{"command":"tray","value":"4X6_photo_paper.png"}']
sel_media
5X7_photo_paper.png
tray
4X6_photo_paper.png
Related
If I run print(CURRENT_JSON) then it prints out ChunkName, ChunkId, m and LINE as string, rather than printing out their values. How to fix it?
CURRENT_JSON = '{"ChunkName": "{ChunkName}", "ChunkData": {"ChunkId": "{ChunkId}", "MasterData": [{"Line": "{m}", "LData": "{LINE}"}]} }'
You can't build JSON manually without considering escaping embedded control characters. For instance, what if one of these fields has a " character? Better to build a python dictionary and then serialize it.
import json
CURRENT_JSON = json.dumps({"ChunkName": ChunkName,
"ChunkData": {"ChunkId": ChunkId,
"MasterData": [{"Line": m, "LData": Line}]} })
I try to convert this String to only the link: {"link":"https://i.imgur.com/zfxsqlk.png"}
I'm trying to create a discord bot, which sends random pictures from the API https://some-random-api.ml/img/red_panda.
With imageURL = json.loads(requests.get(redpandaurl).content) I get the json String, but what do I have to do that I only get the Link like this https://i.imgur.com/zfxsqlk.png
Sorry if my question is confusingly written, I'm new to programming and don't really know how to describe this problem.
You can simply do this:
image_url = requests.get(your_api_url).json()["link"]
Directly use requests.json(), no need to load the string with json.loads and other manual stuff.
What you get from json.loads() is a Python dict. You can access values in the dict by specifying their keys.
In your case, there is only one key-value pair in the dict: "link" is the key and "https://i.imgur.com/zfxsqlk.png" is the value. You can get the link and store it in the value by appending ["link"] to your line of code:
imageURL = json.loads(requests.get(redpandaurl).content)["link"]
After doing an API request I get the json 'data' this has each record in a different set if curly brackets under the results square brackets.
I want to extract the numbers and store/print them separated with a comma.
so requested output
0010041,0010042
I have tried using the below however it comes back with the following error.
TypeError: list indices must be integers or slices, not str
If the results only has one set of brackets it works fine, do I have to convert the multiple results into one so and then extract all the times when 'number' appears?
import json
import sys
#load the data into an element
data={'result': [{'number': '0010041', 'day_of_week': 'monday'}, {'number': '0010042', 'day_of_week': 'tuesday'}]}
#dumps the json object into an element
json_str = json.dumps(data)
#load the json to a string
resp = json.loads(json_str)
print (resp['result'])
print (resp['result']['number'])
Error message is clear: you are trying to access a list of dicts and you aren't doing it correctly.
Replace your last line with:
for i in resp['result']:
print(i['number'])
Update:
As suggested in comments, you can use list comprehension. So to get your desired result, you can do:
print(",".join([i['number'] for i in resp['result']]))
I have below JSON String. Now I want to extract each individual field from that JSON string.
So I decided to create a method parse_json which will accept a variable that I want to extract from the JSON String.
Below is my python script -
#!/usr/bin/python
import json
jsonData = '{"pp": [0,3,5,7,9], "sp": [1,2,4,6,8]}'
def parse_json(data):
jj = json.loads(jsonData)
return jj['+data+']
print parse_json('pp')
Now whenever I an passing pp to parse_json method to extract its value from the JSON String, I always get the error as -
return jj['+data+']
KeyError: '+data+'
Any idea how to fix this issue? As I need to pass the variable which I am supposed to extract from the JSON String?
You probably just want this:
return jj[data]
Your code is trying to look up a key named literally '+data+', when instead what you want to do is look up the key with a name of the function's parameter.
Just use data parameter itself.
Replace following line:
return jj['+data+'] # lookup with `+data+`, not `pp`
with:
return jj[data]
Found this great answer on how to check if a list of strings are within a line
How to check if a line has one of the strings in a list?
But trying to do a similar thing with keys in a dict does not seem to do the job for me:
import urllib2
url_info = urllib2.urlopen('http://rss.timegenie.com/forex.xml')
currencies = {"DKK": [], "SEK": []}
print currencies.keys()
testCounter = 0
for line in url_info:
if any(countryCode in line for countryCode in currencies.keys()):
testCounter += 1
if "DKK" in line or "SEK" in line:
print line
print "testCounter is %i and should be 2 - if not debug the code" % (testCounter)
The output:
['SEK', 'DKK']
<code>DKK</code>
<code>SEK</code>
testCounter is 377 and should be 2 - if not debug the code
Think that perhaps my problem is because that .keys() gives me an array rather than a list.. But haven't figured out how to convert it..
change:
any(countryCode in line for countryCode in currencies.keys())
to:
any([countryCode in line for countryCode in currencies.keys()])
Your original code uses a generator expression whereas (I think) your intention is a list comprehension.
see: Generator Expressions vs. List Comprehension
UPDATE:
I found that using an ipython interpreter with pylab imported I got the same results as you did (377 counts versus the anticipated 2). I realized the issue was that 'any' was from the numpy package which is meant to work on an array.
Next, I loaded an ipython interpreter without pylab such that 'any' was from builtin. In this case your original code works.
So if your using an ipython interpreter type:
help(any)
and make sure it is from the builtin module. If so your original code should work fine.
This is not a very good way to examine an xml file.
It's slow. You are making potentially N*M substring searches where N is the number of lines and M is the number of keys.
XML is not a line-oriented text format. Your substring searches could find attribute names or element names too, which is probably not what you want. And if the XML file happens to put all its elements on one line with no whitespace (common for machine-generated and -processed XML) you will get fewer matches than you expect.
If you have line-oriented text input, I suggest you construct a regex from your list of keys:
import re
linetester = re.compile('|'.join(re.escape(key) for key in currencies))
for match in linetester.finditer(entire_text):
print match.group(0)
#or if entire_text is too long and you want to consume iteratively:
for line in entire_text:
for match in linetester.find(line):
print match.group(0)
However, since you have XML, you should use an actual XML processor:
import xml.etree.cElementTree as ET
for elem in forex.findall('data/code'):
if elem.text in currencies:
print elem.text
If you are only interested in what codes are present and don't care about the particular entry you can use set intersection:
codes = frozenset(e.text for e in forex.findall('data/code'))
print codes & frozenset(currencies)