woneuy01 / python2

0 stars 0 forks source link

Json loads(json to python object) dumps(python object to json) #6

Open woneuy01 opened 4 years ago

woneuy01 commented 4 years ago

json.loads() takes a string as input and produces a python object (a dictionary or a list) as output.

import json a_string = '\n\n\n{\n "resultCount":25,\n "results": [\n{"wrapperType":"track", "kind":"podcast", "collectionId":10892}]}' print(a_string) d = json.loads(a_string) //json to python object print("------") print(type(d)) print(d.keys()) print(d['resultCount'])

print(a_string['resultCount'])


{ "resultCount":25, "results": [ {"wrapperType":"track", "kind":"podcast", "collectionId":10892}]}

<class 'dict'> ['resultCount', 'results'] 25

woneuy01 commented 4 years ago

import json def pretty(obj): return json.dumps(obj, sort_keys=True, indent=2) //dictionary의 key로 sort 하고 indent =2 //json.dumps는 dict등 파이썬 파일을 json으로 변환

d = {'key1': {'c': True, 'a': 90, '5': 50}, 'key2':{'b': 3, 'c': "yes"}}

print(d) print('--------') print(pretty(d))


{'key1': {'c': True, 'a': 90, '5': 50}, 'key2': {'c': 'yes', 'b': 3}}


{ "key1": {"5":50,"a":90,"c":true}, "key2":{"b":3,"c":"yes"} }

woneuy01 commented 4 years ago

nested1 = [['a', 'b', 'c'],['d', 'e'],['f', 'g', 'h']] for x in nested1: print("level1: ") for y in x: print(" level2: " + y)


level1: level2: a level2: b level2: c level1: level2: d level2: e level1: level2: f level2: g level2: h

woneuy01 commented 4 years ago

Write code to create a new list that contains every person’s last name, and save that list as last_names.

info = [['Tina', 'Turner', 1939, 'singer'], ['Matt', 'Damon', 1970, 'actor'], ['Kristen', 'Wiig', 1973, 'comedian'], ['Michael', 'Phelps', 1985, 'swimmer'], ['Barack', 'Obama', 1961, 'president']]

last_names=[]

for lname in info: last_names.append(lname[1])

woneuy01 commented 4 years ago

Use nested iteration to save every string containing “b” into a new list named b_strings.

L = [['apples', 'bananas', 'oranges', 'blueberries', 'lemons'], ['carrots', 'peas', 'cucumbers', 'green beans'], ['root beer', 'smoothies', 'cranberry juice']]

b_strings=[]

for lst in L: for word in lst: if 'b' in word: b_strings.append(word)

print(b_strings)


['bananas', 'blueberries', 'cucumbers', 'green beans', 'root beer', 'cranberry juice']

woneuy01 commented 4 years ago

Irregular structured data

nested1 = [1, 2, ['a', 'b', 'c'],['d', 'e'],['f', 'g', 'h']] for x in nested1: print("level1: ") if type(x) is list: for y in x: print(" level2: {}".format(y)) else: print(x)


level1: 1 level1: 2 level1: level2: a level2: b level2: c level1: level2: d level2: e level1: level2: f level2: g level2: h

woneuy01 commented 4 years ago

Earlier when we discussed cloning and aliasing lists we had mentioned that simply cloning a list using [:] would take care of any issues with having two lists unintentionally connected to each other. That was definitely true for making shallow copies (copying a list at the highest level), but as we get into nested data, and nested lists in particular, the rules become a bit more complicated. We can have second-level aliasing in these cases, which means we need to make deep copies.

original = [['dogs', 'puppies'], ['cats', "kittens"]] copied_version = original[:] print(copied_version) print(copied_version is original) print(copied_version == original) original[0].append(["canines"]) print(original) print("-------- Now look at the copied version -----------") print(copied_version)


[['dogs', 'puppies'], ['cats', 'kittens']] False // the object is different True // the pointing content address is the same [['dogs', 'puppies', ['canines']], ['cats', 'kittens']] -------- Now look at the copied version ----------- [['dogs', 'puppies', ['canines']], ['cats', 'kittens']]

woneuy01 commented 4 years ago

original = [['dogs', 'puppies'], ['cats', "kittens"]]

copied_outer_list = [] for inner_list in original: copied_inner_list = [] for item in inner_list: copied_inner_list.append(item) copied_outer_list.append(copied_inner_list) print(copied_outer_list) original[0].append(["canines"]) print(original) print("-------- Now look at the copied version -----------") print(copied_outer_list)


[['dogs', 'puppies'], ['cats', 'kittens']] [['dogs', 'puppies', ['canines']], ['cats', 'kittens']] -------- Now look at the copied version ----------- [['dogs', 'puppies'], ['cats', 'kittens']]

woneuy01 commented 4 years ago

Or, equivalently, you could take advantage of the slice operator to do the copying of the inner list.

original = [['dogs', 'puppies'], ['cats', "kittens"]] copied_outer_list = [] for inner_list in original: copied_inner_list = inner_list[:] copied_outer_list.append(copied_inner_list) print(copied_outer_list) original[0].append(["canines"]) print(original) print("-------- Now look at the copied version -----------") print(copied_outer_list)


[['dogs', 'puppies'], ['cats', 'kittens']] [['dogs', 'puppies', ['canines']], ['cats', 'kittens']] -------- Now look at the copied version ----------- [['dogs', 'puppies'], ['cats', 'kittens']]

woneuy01 commented 4 years ago

This process above works fine when there are only two layers or levels in a nested list. However, if we want to make a copy of a nested list that has more than two levels, then we recommend using the copy module. In the copy module there is a method called deepcopy that will take care of the operation for yo

import copy original = [['canines', ['dogs', 'puppies']], ['felines', ['cats', 'kittens']]] shallow_copy_version = original[:] deeply_copied_version = copy.deepcopy(original) original.append("Hi there") original[0].append(["marsupials"]) print("-------- Original -----------") print(original) print("-------- deep copy -----------") print(deeply_copied_version) print("-------- shallow copy -----------") print(shallow_copy_version)


-------- Original ----------- [['canines', ['dogs', 'puppies'], ['marsupials']], ['felines', ['cats', 'kittens']], 'Hi there'] //제일 밖의 리스트에 추가된거는 shallow copy에 추가 안되었음 -------- deep copy ----------- [['canines', ['dogs', 'puppies']], ['felines', ['cats', 'kittens']]] -------- shallow copy ----------- [['canines', ['dogs', 'puppies'], ['marsupials']], ['felines', ['cats', 'kittens']]]

woneuy01 commented 4 years ago

res = { "search_metadata": { "count": 3, "completed_in": 0.015, "max_id_str": "536624519285583872", "since_id_str": "0", "next_results": "?max_id=536623674942439424&q=University%20of%20Michigan&count=3&include_entities=1", "refresh_url": "?since_id=536624519285583872&q=University%20of%20Michigan&include_entities=1", "since_id": 0, "query": "University+of+Michigan", "max_id": 536624519285583872 }, "statuses": [ { "contributors": None, "truncated": False, "text": "RT @mikeweber25: I'm decommiting from the university of Michigan thank you Michigan for the love and support I'll remake my decision at the\u2026", "in_reply_to_status_id": None, "id": 536624519285583872, "favorite_count": 0, "source": "<a href=\"http://twitter.com/download/iphone\" rel=\"nofollow\">Twitter for iPhone", "retweeted": False, "coordinates": None, "entities": { "symbols": [], "user_mentions": [ { "id": 1119996684, "indices": [ 3, 15 ], "id_str": "1119996684", "screen_name": "mikeweber25", "name": "Mikey" } ], "hashtags": [], "urls": [] }, . . . .

woneuy01 commented 4 years ago

import json

print(type(res))

print(res.keys())

res2 = res['statuses']

print("----Level 2: a list of tweets-----")

print(type(res2)) # it's a list!

print(len(res2)) # looks like one item representing each of the three tweets

for res3 in res2:

print("----Level 3: a tweet----")

print(json.dumps(res3, indent=2)[:30])

res4 = res3['user']

print("----Level 4: the user who wrote the tweet----")

print(type(res4)) # it's a dictionary

print(res4.keys())

print(res4['screen_name'], res4['created_at'])


31brooks_ Wed Apr 09 14:34:41 +0000 2014 froyoho Thu Jan 14 21:37:54 +0000 2010 MDuncan95814 Tue Sep 11 21:02:09 +0000 2012

woneuy01 commented 4 years ago

for res3 in res['statuses']: print(res3['user']['screen_name'], res3['user']['created_at']) //결론은 한단계식 내려가면서 하면 된다.


31brooks_ Wed Apr 09 14:34:41 +0000 2014 froyoho Thu Jan 14 21:37:54 +0000 2010 MDuncan95814 Tue Sep 11 21:02:09 +0000 2012

woneuy01 commented 4 years ago

http://jsoneditoronline.org/#right=local.sofara

json 파일을 여기에다 카피하면 계층별로 나온다.