I'm pretty new to programming, how would I select a certain part of the JSON file and have it display the value? For example:
{
"name": "John",
"age": 18,
"state": "New York"
}
What would be the code in Python needed to get the value of any of the items by giving it the keyword? (i.e. I give it "name" and the output displays "John")
Put the title in brackets.
myJSON = #that JSON
print(myJSON["name"]) #prints John
print(myJSON["age"]) #prints 18
print(myJSON["state"]) #prints New York
Related
I have a text file including tons of output like this:
<Tons-of-random-text>
...
Received Access-Accept (code=2) length=300
Attribute 2 (User-Name) length=16
Value 'myTextValue1'
Attribute 4 (Bla1) length=16
Value 'myTextValue2'
Attribute 6 (Bla2) length=16
Value 0xABCDEFG
<Tons-of-random-text>
At the end of the day I want to use named capture groups to extract:
the code in the first outlined line.
A list of Attributes
Based on the example above, the desired extract data structe is:
code=2
attributes = [
{
"attribute": "2",
"attribute-name": "User-Name",
"value": "myTextValue1"
},
{
"attribute": "4",
"attribute-name": "Bla1",
"value": "myTextValue2"
},
# ...
]
I'm struggling with finditer and findall... at the end of the day I'm only able to match the first or the last attribute block...
Anybody have a hint for a good regex?
This code will match the line with (code=\d) and what follows for as long as each lines contains "Attribute" or "Value".
/(\(code=\d\).*$(\n^\s*(Attribute|Value).*$)+)/gm
see https://regex101.com/r/HzIW5V/1
Hi I'm trying to solve a problem. I have a json list of products, ex:
[{
"id": 5677240,
"name": "Cønjuntø de Pænelæs æntiæderentes ¢øm 05 Peçæs Pæris",
"quantity": 21,
"price": "192.84",
"category": "Panelas"
},
{
"id": 9628920,
"name": "Lava & Seca 10,2 Kg Sæmsung E¢ø ßußßle ßræn¢æ ¢øm 09 Prøgræmæs de Lævægem",
"quantity": 57,
"price": 3719.70,
"category": "Eletrodomésticos"
}]
But I basically need the "price" to be float like the second product. I have a large list of these products
(Ignore the weird characters I managed to fix it with help from a teacher.) I converted them to python object using this
import json
with open('br2.json', 'r', encoding='utf8') as json_data:
data = json.load(json_data)
I've tried something like this but it doesn't work
for product in data:
product["price"] = product["price"].replace(",", "")
I want to replace the values that are in string with the "" to float
thanks in advance sorry I'm new to python so I don't understand much
You can convert a string to float with float(). So instead of your replace line, try:
product['price'] = float(product['price'])
I have downloaded 5MB of a very large json file. From this, I need to be able to load that 5MB to generate a preview of the json file. However, the file will probably be incomplete. Here's an example of what it may look like:
[{
"first": "bob",
"address": {
"street": 13301,
"zip": 1920
}
}, {
"first": "sarah",
"address": {
"street": 13301,
"zip": 1920
}
}, {"first" : "tom"
From here, I'd like to "rebuild it" so that it can parse the first two objects (and ignore the third).
Is there a json parser that can infer or cut off the end of the string to make it parsable? Or perhaps to 'stream' the parsing of the json array, so that when it fails on the last object, I can exit the loop? If not, how could the above be accomplished?
If your data will always look somewhat similar, you could do something like this:
import json
json_string = """[{
"first": "bob",
"address": {
"street": 13301,
"zip": 1920
}
}, {
"first": "sarah",
"address": {
"street": 13301,
"zip": 1920
}
}, {"first" : "tom"
"""
while True:
if not json_string:
raise ValueError("Couldn't fix JSON")
try:
data = json.loads(json_string + "]")
except json.decoder.JSONDecodeError:
json_string = json_string[:-1]
continue
break
print(data)
This assumes that the data is a list of dicts. Step by step, the last character is removed and a missing ] appended. If the new string can be interpreted as JSON, the infinite loop breaks. Otherwise the next character is removed and so on. If there are no characters left ValueError("Couldn't fix JSON") is raised.
For the above example, it prints:
[{'first': 'bob', 'address': {'zip': 1920, 'street': 13301}}, {'first': 'sarah', 'address': {'zip': 1920, 'street': 13301}}]
For the specific structure in the example we can walk through the string and track occurrences of curly brackets and their closing counterparts. If at the end one or more curly brackets remain unmatched, we know that this indicates an incomplete object. We can then strip any intermediate characters such as commas or whitespace and close the resulting string with a square bracket.
This method ensures that the string is only parsed twice, one time manually and one time by the JSON parser, which might be advantageous for large text files (with incomplete objects consisting of many characters).
brackets = []
for i, c in enumerate(string):
if c == '{':
brackets.append(i)
elif c == '}':
brackets.pop()
if brackets:
string = string[:brackets[0]].rstrip(', \n')
if not string.endswith(']'):
string += ']'
I'm trying to iterate over a JSON list to print out all of the results of the following:
"examples": [
{
"text": "carry all of the blame"
},
{
"text": "she left all her money to him"
},
{
"text": "we all have different needs"
},
{
"text": "he slept all day"
},
{
"text": "all the people I met"
},
{
"text": "10% of all cars sold"
}
],
I've tried to iterate over it by doing:
iterator = 0
json_example = str(json_data['results'][0]['lexicalEntries'][0]['entries'][0]['senses'][0]['examples'][iterator]['text']).capitalize()
for i in json_example:
print(i)
iterator += 1
But this is only printing each letter of the first example, as oppose to the entire example, followed by other entire examples.
Can I iterate over these as I would like to, or do I need to create separate variables with each example?
Following your code and example, it looks like what you need is :
for example in json_data['results'][0]['lexicalEntries'][0]['entries'][0]['senses'][0]['examples']:
print(example["text"])
In your code, by doing json_data['results'][0]['lexicalEntries'][0]['entries'][0]['senses'][0]['examples'][iterator]['text'] you were only accessing the iteratorth item, so, always the first one (iterator=0), and then iterating on the content of the "text" member.
Only index the json data out to 'examples':
json_example = json_data['results'][0]['lexicalEntries'][0]['entries'][0]['senses'][0]['examples']
then treat each element of 'examples' like a dictionary:
for dictionary in json_example:
for key in dictionary:
print(dictionary[key])
This will print out each value correlated with the key 'text', like you want.
I want to be able to read in a file, post.md, like this:
title: Some Title
slug: some-title
author: Joe Smith
date: Jan 23 2015
tags: a, b, c, d
This is the first paragraph of the post.
This is another paragraph.
and generate a python dictionary like this:
post = {
"title": "Some Title",
"slug": "some-title",
"author": "Joe Smith",
"title": datetime.date(2015, 1, 23),
"tags": ["a", "b", "c", "d",],
"body": "This is the first paragraph of the post.\n\nThis is another paragraph."
}
It is acceptable to modify the file input slightly, but can't go full yaml because I want markdown highlighting. Maybe someone who knows pelican's code base better than myself can figure out how it is done there.
As #Carl Groner suggested, this can be done with the Meta-Data Extension to Python Markdown.