Read the first Json Element in a Pythonscript - python

i need the first json object´s name (here in this examole its "object") as a String. The Json looks like this:
{'object':{'a': ['123', '234', '345'], 'b' : '1234'}}
but the objects name switches randomly with the user input. So I need to read the first element of the Json file like list[0] with lists.

Assuming you have a JSON string data
import json
jsondict = json.loads(data)
first = list(jsondict)[0]
This will give you the first object's name.

Related

how to print after the keyword from python?

i have following string in python
b'{"personId":"65a83de6-b512-4410-81d2-ada57f18112a","persistedFaceIds":["792b31df-403f-4378-911b-8c06c06be8fa"],"name":"waqas"}'
I want to print the all alphabet next to keyword "name" such that my output should be
waqas
Note the waqas can be changed to any number so i want print any name next to keyword name using string operation or regex?
First you need to decode the string since it is binary b. Then use literal eval to make the dictionary, then you can access by key
>>> s = b'{"personId":"65a83de6-b512-4410-81d2-ada57f18112a","persistedFaceIds":["792b31df-403f-4378-911b-8c06c06be8fa"],"name":"waqas"}'
>>> import ast
>>> ast.literal_eval(s.decode())['name']
'waqas'
It is likely you should be reading your data into your program in a different manner than you are doing now.
If I assume your data is inside a JSON file, try something like the following, using the built-in json module:
import json
with open(filename) as fp:
data = json.load(fp)
print(data['name'])
if you want a more algorithmic way to extract the value of name:
s = b'{"personId":"65a83de6-b512-4410-81d2-ada57f18112a",\
"persistedFaceIds":["792b31df-403f-4378-911b-8c06c06be8fa"],\
"name":"waqas"}'
s = s.decode("utf-8")
key = '"name":"'
start = s.find(key) + len(key)
stop = s.find('"', start + 1)
extracted_string = s[start : stop]
print(extracted_string)
output
waqas
You can convert the string into a dictionary with json.loads()
import json
mystring = b'{"personId":"65a83de6-b512-4410-81d2-ada57f18112a","persistedFaceIds":["792b31df-403f-4378-911b-8c06c06be8fa"],"name":"waqas"}'
mydict = json.loads(mystring)
print(mydict["name"])
# output 'waqas'
First you need to convert the string into a proper JSON Format by removing b from the string using substring in python suppose you have a variable x :
import json
x = x[1:];
dict = json.loads(x) //convert JSON string into dictionary
print(dict["name"])

How to convert list of given order to json of given order

I have a list of this order
text = ['code1','matrix result from one','code2','matrix result from two']
I want output in json as :
text = {"code1" : "matrix result from one", "code2" : "matrix result from two"}
How can i do this? Thanks in advance
Use json.dumps() to convert data to a string of a JSON object and json.loads() to create a JSON object.
import json
text = ['code1','matrix result from one','code2','matrix result from two']
json_dump = json.dumps(text)
print(json_dump)

How to remove numbers from json in python

I having some json format like
json= 5843080158430803{"name":"NAME", "age":"56",}
So, how i get {"name":"NAME", "age":"56",} Using regex/split (which one is bets method for it) in Python.
Thanks in Advance...
Split the first occurance of { into an array, and get the second element in the array.
We also have to add the { again because its removed by the split function
json = '5843080158430803{"name":"NAME", "age":"56",}'
json = '{' + json.split('{', 1)[1]
print(json)
Result: {"name":"NAME", "age":"56",}
perhaps you could split at at the first { and then replace the part prior to it.
I am assuming the json you have above is actually a string. Then you could do:
json_prefix = json.split("{")
json = json.replace(json_prefix, "")

JSON from streamed data in Python

I am simply trying to keep the following input and resulting JSON string in order.
Here is the input string and code:
import json
testlist=[]
# we create a list as a tuple so the dictionary order stays correct
testlist=[({"header":{"stream":2,"function":3,"reply":True},"body": [({"format": "A", "value":"This is some text"})]})]
print 'py data string: '
print testlist
data_string = json.dumps(testlist)
print 'json string: '
print data_string
Here is the output string:
json string:
[{"body": [{"format": "A", "value": "This is some text"}], "header": {"stream": 2, "function": 3, "reply": true}}]
I am trying to keep the order of the output the same as the input.
Any help would be great. I can't seem to figure this one point.
As Laurent wrote your question is not very clear, but I give it a try:
OrderedDict.update adds in the above case the entries of databody to the dictionary.
What you seem to want to do is something like data['body'] = databody where databody is this list
[{"format":"A","value":"This is a text\nthat I am sending\n to a file"},{"format":"U6","value":5},{"format":"Boolean","value":true}, "format":"F4", "value":8.10}]
So build first this list end then add it to your dictionary plus what you wrote in your post is that the final variable to be parse into json is a list so do data_string = json.dumps([data])

How to fetch single item out of long string?

I have a very string as output of function as follows:
tmp = <"last seen":1568,"reviews [{"id":15869,"author":"abnbvg","changes":........>
How will I fetch the "id":15869 out of it?
The string content looks like JSON, so either use the json module or use a regular expression to extract the specific string you need.
The data looks like a JSON string. Use:
try:
import json
except ImportError:
import simplejson as json
tmp = '"last seen":1568,"reviews":[{"id":15869,"author":"abnbvg"}]'
data = json.loads('{{{}}}'.format(tmp))
>>> print data
{u'reviews': [{u'id': 15869, u'author': u'abnbvg'}], u'last seen': 1568}
>>> print data['reviews'][0]['id']
15869
Note that I wrapped the string in { and } to make a dictionary. You might not have to do that if the actual JSON string is already encapsulated with braces.
If id is the only thing you need from the string and it will always be something like {"id":15869,"author":"abnbvg"..., then you can go with sinple string split instead of json conversion.
tmp = '"last seen":1568,"reviews" : [{"id":15869,"author":"abnbvg","changes":........'
tmp1 = tmp.split('"id":', 1)[1]
id = tmp1.split(",", 1)[0]
Please note that tmp1 line may raise IndexError in case there is no "id" key found in the string. You can use -1 instead of 1 to side step. But in this way, you can report that "id" is not found.
try:
tmp1 = tmp.split('"id":', 1)[1]
id = tmp1.split(",", 1)[0]
except IndexError:
print "id key is not present in the json"
id = None
If you do really need more variables from the json string, please go with mhawke's solution of converting the json to dictionary and getting the value. You can use ast.literal_eval
from ast import literal_eval
tmp = '"last seen":1568,"reviews" : [{"id":15869,"author":"abnbvg","changes":........'
tmp_dict = literal_eval("""{%s}"""%(tmp))
print tmp_dict["reviews"][0]["id"]
In the second case, if you need to collect all the "id" keys in the list, this will help:
id_list =[]
for id_dict in tmp_dict["reviews"]:
id_list.append(id_dict["id"])
print id_list

Categories

Resources