Parse a string into Dictionary [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a string which is of the form dictionary for sure.
I need to parse it and store it as a dictionary in python.
What i have tried is this:
myObj={}
tmp=""
if ':' in line:
key,value = line.split(':')
key = key.strip('"')
value = value.lstrip(' ').rstrip(',')
if value == '{':
tmp += key + '.'
if value == '}':
tmp = ''
if(value!="{"):
myObj[tmp + key] = value
Reading Line by Line and parsing it. But I am facing problems with different kind of formats.
For E.G.
{
"id": 1,
"name": "Foo",
"price": 123,
"tags": [ "Bar", "Eek" ],
"stock": {
"warehouse": 300,
"retail": 20
}
}
No use of eval or any built in function or library like json. Can I use regex here?
How do I do this?

You have JSON data, use the json library to parse it:
import json
data = json.loads(yourstring)
Python comes with batteries included, don't reinvent the wheel.

Related

use list values as keys to dict with keys [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 months ago.
Improve this question
I have a dictionary
foo = {"/" : {"bar":"returnme"} }
and a list
example = ["/","bar"]
how do I use the list to return the value in "bar" ? (i.e. identical output to
foo["/"]["bar"] )
For clarity the value of the example list changes, the example could also be:
foo = {"/" : {"bar": {"morefoo": {"returnme"}} }}
example = ["/","bar","morefoo"]
foo[example] --> "returnme"
For other functionality in the script I will need to be able to use the example list to add/remove things to the 'final' dictionary.
You have to iteratively retrieve elements from a dictionary.
def get(tree, keys):
current = tree
for key in keys:
current = current[key]
return current
and it works:
>>> get({"/": {"bar": "returnme"}}, ["/", "bar"])
'returnme'
>>> get({"/": {"bar": {"morefoo": "returnme"}}}, ["/", "bar", "morefoo"])
'returnme'
>>>

How can I organize my code according to output that I want? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 12 months ago.
Improve this question
I have the code below.
import json
name = " "
username = " "
ip_address = " "
with open('data6.json', 'r') as myfile:
data = json.load(myfile)
for i in data:
print(i[0].get('Manufacturer'))
print(i[0].get('Name'))
print(i[0].get('IPAddress'))
The output is the code like that:
VMware, Inc.
DC01
None
None
None
['192.168.1.240,fe80::350e:d28d:14a5:5cbb']
None
DC01
None
But i want an output like:
VMware, Inc.
DC01
['192.168.1.240,fe80::350e:d28d:14a5:5cbb']
How can i organize my code according to output that i want?
data6.json is like in the below:
[[{"Manufacturer": "VMware, Inc.", "Model": "VMware7,1", "Name": "DC01"}], [{"Index": "1", "IPAddress": ["192.168.1.240,fe80::350e:d28d:14a5:5cbb"]}], [{"Name": "DC01", "UserName": null}]]
If you load your initial json File you have:
one list -> contains 3 one-element lists -> contains the dict
If you have more of these nestes Lists in files, I would recommend to flatten them
If you want your data you have to access the correct one-element list, first index, then get the element in the one-element list, then choose the right value from the dict. Additionally you should close your file handler to close all resources before further working.
with open('data6.json', 'r') as myfile:
data = json.load(myfile)
print(data[0][0]['Manufacturer'])
print(data[0][0]['Name'])
print(data[1][0]['IPAddress'])

What is the best way to parse the following text in python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I want to use the following text, and parse it to python, but can't find a good way for that
the content is in a text file, and I want to use the data in python.
what kind of type to use? I want to populate it to a menu.
"us-west-2": {
"focal-amd64": "ami-06e54d05255faf8f6",
"rhel7.5-x86_64": "ami-6f68cf0f",
"xenial-amd64": "ami-09b42c38b449cfa59",
"bionic-amd64": "ami-03804ed633fe58109",
"rhel8-x86_64": "ami-02f147dfb8be58a10"
},
"us-east-1": {
"oracle6.5": "ami-c034c5ad",
"rhel7.5-x86_64": "ami-0394fe9914b475c53",
"rhel7.7-x86_64": "ami-0916c408cb02e310b",
"trusty-amd64": "ami-0d859172c8670bbcd",
"xenial-amd64": "ami-028d6461780695a43",
"rhel7.6-x86_64": "ami-08a7d2bfef687328f",
"aws-ena": "ami-ccd280db",
"rhel8-x86_64": "ami-098f16afa9edf40be",
"rhel7.9-x86_64": "ami-005b7876121b7244d",
"bionic-amd64": "ami-07025b83b4379007e",
"centos6.9-x86_64": "ami-25491433",
"focal-amd64": "ami-0dba2cb6798deb6d8"
},
"us-east-2": {
"focal-amd64": "ami-07efac79022b86107",
"rhel7.9-x86_64": "ami-0d2bf41df19c4aac7",
},
"eu-central-1": {
"bionic-amd64": "ami-054e21e355db24124",
"xenial-amd64": "ami-05710338b6a5013d1",
},
"eu-west-1": {
"focal-amd64": "ami-06fd8a495a537da8b",
"rhel7.5-x86_64": "ami-02ace471",
"rhel7.6-x86_64": "ami-04c89a19fea29f1f0",
"rhel7.9-x86_64": "ami-020e14de09d1866b4",
"bionic-amd64": "ami-0727f3c2d4b0226d5",
"rhel8-x86_64": "ami-08f4717d06813bf00"
},
"ap-northeast-1": {
"bionic-amd64": "ami-003371bfa26192744",
"xenial-amd64": "ami-097beac0bacfefe65",
"focal-amd64": "ami-09b86f9709b3c33d4",
}
Your data is almost in json format: if you
add enclosing brackets {} around it, and remove any commas , before a closing
bracket (there are 3 of them), your data will be fully json-compliant.
Now assuming your data is in a file called foobar.json, the following code will
parse it into a python dictionary named d:
import json
with open('foobar.json', 'r') as f:
d = json.load(f)
You can now easily access and use your data, for example
print(d['us-west-2']['focal-amd64'])
will print ami-06e54d05255faf8f6.

How to parse a JSON object? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I know there are a lot of questions like these but I am not able to find an answer to my question. Or probably, I am missing something here. The format of my JSON is:
{
"fields": [
{
"type": "long",
"name": "UniqId",
"data": "True"
},
{
"type": "string",
"name": "Name",
"data": "True"
},
{
"type": "string",
"name": "Address",
"data": "False"
}
],
"type": "struct"
}
I just want name and type to be extracted and appended to a list. First element to be name and second to be type.
The above format is saved in a variable json_dump. And when I do:
for k in json_dump1.iteritems():
print k
It gives me an error
"AttributeError: 'str' object has no attribute 'iteritems".
I would really appreciate the help. Thanks.
json_dump1 is a string, so you need to parse it into an object first. This can be done with the json library:
import json
parsed_json = json.loads(json_dump1)
It sounds like you also want to do some comprehension on this. It's unclear exactly how you want the name and type values to be stored, but you would want something like this to iterate over parsed_json:
results = []
for f in parsed_json['fields']:
results.append(f['name'])
results.append(f['type'])
For cases like this, it's better to think of the json as a dictionary containing nested lists or dictionaries within them. So if you treat them as such and iterate over the lists/keys you should be fine. In this case, the first key is fields, after that we have a number of lists that each contain a dictionary, so we iterate over each of these lists and extract the desired keys (name and type):
name_list = []
type_list = []
for i in json_file['fields']:
name_list.append(i['name'])
type_list.append(i['type'])
print name_list
print type_list
Output:
['UniqId', 'Name', 'Address']
['long', 'string', 'string']
You can also create a dictionary in which you will append these values:
json_values = {'name':type_name,'list':type_list}
Of course you can define this first and append the values to the lists in the dictionaries:
json_values = {'name':[],'list':[]
name_list = []
type_list = []
for i in json_file['fields']:
json_values['name'].append(i['name'])
json_values['list'].append(i['type'])

How can I turn integers into strings in a dict using Python? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I'm creating a dictionary from the college scorecard API, but I'm having trouble joining integer queries to my dictionary (ie. "2015.student.size"). How would I do that in my code? I've tried "str() for f in", but that doesn't seem to work.
This is what I've written in Python so far:
import requests
import json
def main():
url = 'https://api.data.gov/ed/collegescorecard/v1/schools.json'
payload = {
'api_key': "api_key_here",
'_fields': ','.join([
'school.name',
'school.school_url',
'school.city',
'school.state',
'school.zip',
]),
'school.operating': '1',
'2015.academics.program_available.assoc_or_bachelors': 'true',
'2015.student.size__range': '1..',
'school.degrees_awarded.predominant__range': '1..3',
'school.degrees_awarded.highest__range': '2..4',
'id': '240444',
}
data = requests.get(url, params=payload).json()
for result in data['results']:
print(','.join(result.values()))
main()
What happens when I run the program:
vagrant#vagrant:/vagrant/scripts$ python test.py
Madison,www.wisc.edu,University of Wisconsin-Madison,WI,53706-1380
When I add "print data":
{u'results': [{u'school.city': u'Madison', u'school.school_url': u'ww
w.wisc.edu', u'school.name': u'University of Wisconsin-Madison', u'sc
hool.state': u'WI', u'school.zip': u'53706-1380'}], u'metadata': {u'p
er_page': 20, u'total': 1, u'page': 0}}
I think you are making this more difficult than necessary. Instead of the for loop, you can do
print(data)
Or if you want each dictionary from the list to be on its own line, instead of
print(','.join(result.values()))
Just do
print(result)

Categories

Resources